<?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 Alexander Sack on Medium]]></title>
        <description><![CDATA[Stories by Alexander Sack on Medium]]></description>
        <link>https://medium.com/@pisymbol?source=rss-e13ebfdd5f62------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*fopViO9LfaIUoZLYvl3bMA.jpeg</url>
            <title>Stories by Alexander Sack on Medium</title>
            <link>https://medium.com/@pisymbol?source=rss-e13ebfdd5f62------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:51:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pisymbol/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[Decoding Decentralization]]></title>
            <link>https://medium.com/coinmonks/decoding-decentralization-f3af30068e75?source=rss-e13ebfdd5f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3af30068e75</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <dc:creator><![CDATA[Alexander Sack]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 01:39:48 GMT</pubDate>
            <atom:updated>2023-04-26T00:21:02.984Z</atom:updated>
            <content:encoded><![CDATA[<p>An Ethereum Blockchain Data Primer: Part I</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNHmihYILLJOsM6wx3cxdQ.png" /></figure><h3>Introduction</h3><p>Blockchains are interesting beasts — they come in a <a href="https://www.coindesk.com/learn/what-are-the-four-kinds-of-blockchains/">variety of shapes and sizes</a> with <a href="https://www.blockchain-council.org/blockchain/solana-vs-polygon-vs-ethereum/">vastly different feature sets and performance characteristics</a>.</p><p>Yet at their core they are all still basically, <a href="https://en.wikipedia.org/wiki/Distributed_database"><em>distributed databases</em></a>. Ethereum is no different.</p><p>Think of this way: I want you to imagine that each block appended to the chain is like an INSERT operation of new transactions to a database.</p><p>Each transaction in-turn describes some kind of state change, i.e. a token was burned, a <a href="https://www.cryptokitties.co/">Cryptokitty</a> was born, a <a href="https://boredapeyachtclub.com/">Bored Ape</a> was sold etc. That’s basically a blockchain.</p><p>Now a few hard-core crypto-anarchists might accuse me of oversimplifying things, and I wouldn’t argue (for a variety of reasons).</p><p>However, the database analogy is still a useful one since it provides a familiar framework to work under when analyzing raw blockchain data.</p><p>In this series of articles, I’m going to give you a gentle introduction to Ethereum’s data primitives and how to access and extract some useful information out of them — let’s decode decentralization together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNvkbGOXZlf2CxFC1jrr8A.jpeg" /></figure><h3>Call Me Ishmael</h3><p>Let’s pretend you want to track “whales”, or wallets that hold the majority of a certain token type.</p><p>For example, let’s find out how many wallets contain the <a href="https://en.wikipedia.org/wiki/Non-fungible_token">NFT</a> minted by the <a href="https://murakamiflowers.kaikaikiki.com/">Murakami Flowers Official 2022 Collection</a>, a cool collection of dot art based on 1970s Japanese television.</p><p>Intuitively, you would need to know NFT’s total distribution across all of its holder’s wallets.</p><p>But how do you find that information?</p><p>A quick way would be to go a site like <a href="https://etherscan.io/">Etherscan</a> or <a href="https://opensea.io/">OpenSea</a>, search for the token’s contract address, and consult either the<strong> </strong><a href="https://etherscan.io/token/0x7d8820fa92eb1584636f4f5b8515b5476b75171a#balances"><strong>Holders</strong></a> or <a href="https://opensea.io/collection/murakami-flowers-2022-official/analytics"><strong>Analytics</strong></a> table respectively.</p><p>Alright, but <em>how did Etherscan construct their </em><strong><em>Holders </em></strong><em>table to begin with</em>?</p><p>Well, I assure you they didn’t just “query the blockchain” — at least not in the traditional sense.</p><p>In fact, the only real native way to determine how many of a certain token type a wallet owns is to scan the blockchain from <strong>genesis</strong> (the first block) to the latest one (the delta is typically referred to as the<strong> block height</strong>) looking for transactions of Murakami Flowers NFTs.</p><p><em>(Note: Technically, if you know the block number or approximate date that contained the transaction that deployed the token’s smart contract or its first transfer event then you don’t necessarily have to start from genesis and can short-circuit the scan. But let’s onboard this contract blind for learning purposes!)</em></p><h3>Accessing the Data</h3><p>Before we start looking at real blockchain data, we first need to understand how to access it.</p><p>As with most distributed ledgers, every node has a copy of the current state of the chain.</p><p>However, depending on whether your node is <a href="https://www.quicknode.com/guides/infrastructure/node-setup/ethereum-full-node-vs-archive-node/">a full node or an archival one</a> will determine how much block lineage is currently available.</p><p>A full node only contains the last 128 blocks. That’s all it needs to guarantee it’s on the current canonical line.</p><p>An archival node on the other hand, has the entire history of transactions from genesis, which at the time of this writing is approximately 2TB in size.</p><p>So there are a few different ways to access an archival node:</p><ul><li>Run your own <a href="https://ethereum-on-arm-documentation.readthedocs.io/en/latest/">archival node as a local endpoint</a></li><li>Subscribe to a node provider’s endpoint such as <a href="https://www.quicknode.com/">QuickNode</a>, <a href="https://www.infura.io/">Infura</a>, <a href="https://www.alchemy.com/">Alchemy</a>, and soon <a href="https://cloud.google.com/blog/products/infrastructure-modernization/introducing-blockchain-node-engine">Google</a></li><li>Download <a href="https://cloud.google.com/blog/products/data-analytics/ethereum-bigquery-public-dataset-smart-contract-analytics">Google’s public Ethereum datasets</a> hosted on BigQuery via their open-sourced <a href="https://github.com/blockchain-etl/ethereum-etl">ethereum-etl</a> tool</li></ul><p>Outside of that last option, all endpoint access will be via the <a href="https://ethereum.org/en/developers/docs/apis/json-rpc/">official JSON-RPC specification</a>, a REST based API that allows any client to interact with the Ethereum blockchain directly and what we’ll be covering in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Ow29VF3IUu1HsXbySRpZTg.png" /></figure><h3>Blocks, Transactions, and Logs</h3><p>There are three fundamental data types when working with raw Ethereum data: the blocks (shock!), the transactions contained within those blocks, and the logs that those transactions generate.</p><p>Let’s use the JSON-RPC to dump the latest block (as I type this) using the <a href="https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber"><strong>eth_blockNumber</strong></a><strong> </strong>API.</p><p>We’ll use the venerable <a href="https://curl.se/">curl</a> command to make requests and the <a href="https://stedolan.github.io/jq/">jq</a> command to format their output.</p><pre>$ curl -s -X POST  -H &#39;Content-Type: application/json&#39; http://localhost:8545<br>  --data &#39;{&quot;id&quot;: 1, &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;method&quot;: &quot;eth_blockNumber&quot;, &quot;params&quot;: [] }&#39; | jq .&#39;<br>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;result&quot;: &quot;0x103ee72&quot;<br>}</pre><ul><li>My endpoint is a locally hosted one, so I’m using the standard <a href="https://geth.ethereum.org/">geth</a> port or <strong>8545. </strong><em>(Note: If you use a managed node service like QuickNode, specify the URL they assign you, usually it doesn’t contain a port but does include an API key as a query parameter)</em></li><li>The JSON string I’m passing specifies the <strong>method</strong> and <strong>params</strong> I’d like to call. In this case, it’s <strong>eth_blockNumber</strong> with no arguments.</li><li>The JSON response string has the <strong>result </strong>and the current <strong>block height</strong> is <strong>0x103ee72</strong> (17034866).</li><li>Notice that the JSON-RPC treats block numbers as hexadecimal strings not numbers.</li></ul><p>So if we need to scan from genesis to the latest block, that means we need to sift through over 17 million blocks looking for transactions of interest!</p><p>Let’s actually dump the latest block to get a sense of what it looks like by using the <a href="https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber"><strong>eth_getBlockByNumber</strong></a> API:</p><pre>$ curl -s -X POST  -H &#39;Content-Type: application/json&#39; http://localhost:8545<br>  --data &#39;{&quot;id&quot;: 1, &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;method&quot;: &quot;eth_getBlockByNumber&quot;, &quot;params&quot;: [&quot;0x103ee72&quot;, false]}&#39; | jq .<br>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;result&quot;: {<br>    &quot;baseFeePerGas&quot;: &quot;0x4bf9fd279&quot;,<br>    &quot;difficulty&quot;: &quot;0x0&quot;,<br>    &quot;extraData&quot;: &quot;0x66696e657374206172746973616e616c20626c6f636b73&quot;,<br>    &quot;gasLimit&quot;: &quot;0x1c9c380&quot;,<br>    &quot;gasUsed&quot;: &quot;0xdea4db&quot;,<br>    &quot;hash&quot;: &quot;0x313d2357584c1edd0ede55cf7b380bc5750642702e7f9aa50c80c07f3f42ad35&quot;,<br>    &quot;logsBloom&quot;: &quot;0x61b9f9619942db3ad8284167f30dd6b61aeae092af231f4a10010948f4921012fe000fc96369ca0d58f57886cf10bd48cec71e5cbed13c4d3a33c06593e97ae338ceff2e6e0028caab23fe4e9bf783f8c2f6c0a38ad408d453c5ddcc81f32171861491525edf22f14e90daa888214c91e657e49567701e30721063dcbabf21ec3e93855cc2e73082ad4ecc49b787167da6423ed3ef5166e8867bd0d722182d61fecb1d63cbc1621c3c50f1eff9b214c146c1c1c1ed889c9ee7648db9335b63d9419e5d1ec64b3d51404aa2290e3d9484d342f01527e8a0502224d0332c74b4e8bcb6be59031114911d07d6a885a07900869fe1985b5869ddbb3d3ad1b2d17d1b&quot;,<br>    &quot;miner&quot;: &quot;0x1e54945fbf1872e34d76b7d72151b861704df8b2&quot;,<br>    &quot;mixHash&quot;: &quot;0xa5bb6f039f871f93276f71da4608b4020ced6cca67eed50d52d56d92261c68f6&quot;,<br>    &quot;nonce&quot;: &quot;0x0000000000000000&quot;,<br>    &quot;number&quot;: &quot;0x103ee72&quot;,<br>    &quot;parentHash&quot;: &quot;0x768dc94136443da9220ce1bd762af4e147e897dd64b608c73ee1158cdb4c0933&quot;,<br>    &quot;receiptsRoot&quot;: &quot;0x4f2c78733b08777cfc280c794a4b1ab63edfa55d18c5e42914bc7063b56d4ce5&quot;,<br>    &quot;sha3Uncles&quot;: &quot;0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347&quot;,<br>    &quot;size&quot;: &quot;0x1f45c&quot;,<br>    &quot;stateRoot&quot;: &quot;0x0eaa3502265f106aa6dc2b4501222015d88f0eb671dd1cbc2cad0400d5181964&quot;,<br>    &quot;timestamp&quot;: &quot;0x64373027&quot;,<br>    &quot;totalDifficulty&quot;: &quot;0xc70d815d562d3cfa955&quot;,<br>    &quot;transactions&quot;: [<br>      &quot;0x9f5dc17b654c8e2d1d21e607369b624c5b1b92beb494e624dc3ea51443e7da38&quot;,<br>      &quot;0xc87b4344d71f9388fc89c7da47fd9e828c9e7f081111e2f92ca2d1eec302c4ea&quot;,<br>      &quot;0x826b61c9892b620cc59b06be405d498b5a84b7f25b88cf641938f9c4b0940460&quot;,<br>...<br> &quot;transactionsRoot&quot;: &quot;0xcc3e13a69a79cdab87d68a79ffd536d61e11cc489a358bc761073cd43d4a945e&quot;,<br>    &quot;uncles&quot;: []<br>  }<br>}</pre><ul><li>Again, same as before: We are sending a POST request to our archive node’s endpoint with the <strong>method</strong> and <strong>params</strong> arguments.</li><li>We want to dump block number <strong>0x103ee72 </strong>but don’t want to the full transactions expanded by sending <strong>false</strong> as the second argument.</li><li>The <strong>result</strong> contains the JSON string that represents this block.</li></ul><p>Notice that the overwhelming majority of fields have more to do with internal chain house-keeping than anything about the transactions that are contained within it.</p><p>How many transactions were in this block?</p><p>Let’s count them by parsing the the <strong>transactions</strong> array:</p><pre>$ curl -s -X POST  -H &#39;Content-Type: application/json&#39; http://localhost:8545<br>  --data &#39;{&quot;id&quot;: 1, &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;method&quot;: &quot;eth_getBlockByNumber&quot;, &quot;params&quot;: [&quot;0x103ee72&quot;, false]}&#39; | jq .result.transactions[] | wc -l<br>118</pre><p>So there were 118 valid transactions this miner <strong>(0x1e5494…)</strong> validated and assembled into a block.</p><p>If we instead call <strong>eth_getBlockByNumber</strong> but pass <strong>true </strong>for the second argument, we can see the full transaction structures as well:</p><pre>$ curl -s -X POST  -H &#39;Content-Type: application/json&#39; http://localhost:8545<br>  --data &#39;{&quot;id&quot;: 1, &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;method&quot;: &quot;eth_getBlockByNumber&quot;, &quot;params&quot;: [&quot;0x103ee72&quot;, true]}&#39; | jq .result.transactions[0]<br>{<br>  &quot;blockHash&quot;: &quot;0x313d2357584c1edd0ede55cf7b380bc5750642702e7f9aa50c80c07f3f42ad35&quot;,<br>  &quot;blockNumber&quot;: &quot;0x103ee72&quot;,<br>  &quot;from&quot;: &quot;0xd108fd0e8c8e71552a167e7a44ff1d345d233ba6&quot;,<br>  &quot;gas&quot;: &quot;0x5208&quot;,<br>  &quot;gasPrice&quot;: &quot;0x714350ab9&quot;,<br>  &quot;maxPriorityFeePerGas&quot;: &quot;0x254953840&quot;,<br>  &quot;maxFeePerGas&quot;: &quot;0xcd289c5f5&quot;,<br>  &quot;hash&quot;: &quot;0x9f5dc17b654c8e2d1d21e607369b624c5b1b92beb494e624dc3ea51443e7da38&quot;,<br>  &quot;input&quot;: &quot;0x&quot;,<br>  &quot;nonce&quot;: &quot;0x51ac3&quot;,<br>  &quot;to&quot;: &quot;0x4fdd49a9e72944c068714b278b65537f6829c8b2&quot;,<br>  &quot;transactionIndex&quot;: &quot;0x0&quot;,<br>  &quot;value&quot;: &quot;0xa69f4d2ff74000&quot;,<br>  &quot;type&quot;: &quot;0x2&quot;,<br>  &quot;accessList&quot;: [],<br>  &quot;chainId&quot;: &quot;0x1&quot;,<br>  &quot;v&quot;: &quot;0x1&quot;,<br>  &quot;r&quot;: &quot;0xfd9851bc4a8afc84c3525a2f8b67cffda03a4a6be84b10b6f1adc31df587e87a&quot;,<br>  &quot;s&quot;: &quot;0x74eb3b7497b8e4f2cdf8e9246d063b2833745b1ae02b98e5de1853e53d2de241&quot;<br>}</pre><ul><li>Most of the information is again still related to chain bookkeeping.</li><li>However, at least the transaction structure has both a<strong> from</strong> and <strong>to</strong> address as well as a <strong>value </strong>field.</li><li>Note that the <strong>value </strong>is in Wei and is a hexadecimal string.</li><li>If we search for the <strong>hash</strong> (<strong>0x9f5dc</strong>…) address on <a href="https://etherscan.io/tx/0x9f5dc17b654c8e2d1d21e607369b624c5b1b92beb494e624dc3ea51443e7da38">Etherscan</a>, we see that neither the <strong>to</strong> or the <strong>from</strong> address really resolve into anything meaningful.</li><li>This is just a private transaction between two parties (decentralization at its finest!)</li></ul><p>Thus far, our journey hasn’t resulted in any real analytic gold. However, let’s dive a little deeper on what happens when a flower is bought or sold and how that might help us find the set of transactions (and the wallets referenced in them) we’re looking for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*lhaIue-6cMse8WhCTmk4ug.jpeg" /></figure><h3>Smart Contracts</h3><p>The way a user buyers or sells a token is through a smart contract.</p><p>In fact, the act of calling a smart contract is the primary mechanism a transaction is first initiated.</p><p>If you aren’t familiar with smart contracts though, one can think of them as a glorified set of <a href="https://en.wikipedia.org/wiki/Stored_procedure">stored procedures</a> — it lives on the chain (read: it has an address), has access to some local state, and executes as part of the chain’s run-time.</p><p>Now the state that a contract maintains can be stored in either account storage or event logs.</p><p>Account storage is basically the smart contract’s local storage (think: <a href="https://en.wikipedia.org/wiki/Memory_management#HEAP">heap</a>) and is always directly accessible from within the contract itself but not outside clients.</p><p>Event logs on the other hand, provide a lower cost storage option for contracts to record an audit trail of state changes. These state changes are then captured in the contract’s logs area and are designed for outside client consumption.</p><p>If this sounds a lot like <a href="https://en.wikipedia.org/wiki/Change_data_capture">change-data capture</a> in traditional databases, you’d be right!</p><p>But how does say OpenSea know what function to call in the <a href="https://etherscan.io/address/0x7d8820fa92eb1584636f4f5b8515b5476b75171a#code#F1#L1">Murakami Flower contract</a> when someone presses the buy button?</p><p>Well, although a smart contract can manage a digital asset anyway it so chooses, the overwhelming majority of tokens follow a standard that the Ethereum community has put forth.</p><p>They are called <a href="https://eips.ethereum.org/erc">Ethereum Improvement Proposals</a> and are indexed by an ERC number (think RFCs). Each standard defines an interface the contract must implement.</p><p>Our Murakami Flowers NFT happens to follow the ERC-721 specification, which outlines how tokens are transferred, what functions to call, and most importantly, <em>what events they emit.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*2I3HtuOtQkNrotGfUcWspQ.jpeg" /></figure><h3>Events vs. Logs</h3><p>If you read enough blockchain articles, you’ll notice that the concept of an event and log are used almost interchangeably.</p><p>But they are different:</p><ul><li><em>Events</em> are emitted in smart contract code (usually when a state change occurs).</li><li><em>Logs</em> are generated from them and act as an audit trail for outside application consumption.</li></ul><p>But how do we know what events are emitted from the Murakami Flowers contract?</p><p>Through ts <a href="https://docs.soliditylang.org/en/v0.8.13/abi-spec.html">Application Binary Interface (ABI)</a>, a JSON document that defines the contract’s various functions <em>as well as what events it emits. </em>These specifications are usually freely available on Etherscan (and other places too, e.g. source control).</p><p>Let’s dump the <a href="http://api.etherscan.io/api?module=contract&amp;action=getabi&amp;address=0x7d8820fa92eb1584636f4f5b8515b5476b75171a&amp;format=raw">Murakami Flower contract’s ABI</a> and parse it for events:</p><pre>$ curl -s &quot;http://api.etherscan.io/api?module=contract&amp;action=getabi&amp;address=0x7d8820fa92eb1584636f4f5b8515b5476b75171a&amp;format=raw&quot; | jq &#39;.[] | select(.type == &quot;event&quot;) | .name&#39;<br>&quot;Approval&quot;<br>&quot;ApprovalForAll&quot;<br>&quot;OwnershipTransferred&quot;<br>&quot;RoleAdminChanged&quot;<br>&quot;RoleGranted&quot;<br>&quot;RoleRevoked&quot;<br>&quot;Transfer&quot;</pre><p>So this contract emits a total of 7 events! Out of those, that <em>Transfer</em> one looks like it has potential!</p><h3>The Anatomy of an Event</h3><p>If you look at <a href="https://etherscan.io/address/0x7d8820fa92eb1584636f4f5b8515b5476b75171a#events">Etherscan’s <strong>Events</strong> table</a> for the Murakami contract you can see some of these events in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uACcyC0k4E2XxGu7rKpVg.jpeg" /></figure><p>Let’s drill down and look at a specific <em>Transfer</em> event from one of those transactions to get a sense of what it contains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Et_FAOpeHT1VOmIlB7coAQ.jpeg" /></figure><ul><li>Each event log entry contains the contract <strong>address</strong> from which it originated. Murakami Flower’s contract address is <strong>0x7D882...</strong></li><li>Let’s skip <strong>name</strong> for now as it is a derived value and not actually part of the raw data itself. The output that you see here is actually just from the ABI document I referenced above.</li><li>Every log entry has all of its contents distributed over the <strong>topics array</strong> and the <strong>data </strong>entry.</li><li>The first entry of the <strong>topics</strong> array is always the event’s function signature encoded using Ethereum’s default hashing algorithm, <a href="http://emn178.github.io/online-tools/keccak_256.html">Keccak-256</a>.</li><li>The <strong>last three entries of the topics</strong> <strong>array</strong> are used by smart contracts to help in filtering them (see below).</li></ul><p>So per above, we know the Murakami Flowers contract emits a <em>Transfer </em>event from its ABI document:</p><pre>$ curl -s &quot;http://api.etherscan.io/api?module=contract&amp;action=getabi&amp;address=0x7d8820fa92eb1584636f4f5b8515b5476b75171a&amp;format=raw&quot;   | jq &#39;.[] | select(.type == &quot;event&quot; and .name == &quot;Transfer&quot;)&#39;<br>{<br>  &quot;anonymous&quot;: false,<br>  &quot;inputs&quot;: [<br>    {<br>      &quot;indexed&quot;: true,<br>      &quot;internalType&quot;: &quot;address&quot;,<br>      &quot;name&quot;: &quot;from&quot;,<br>      &quot;type&quot;: &quot;address&quot;<br>    },<br>    {<br>      &quot;indexed&quot;: true,<br>      &quot;internalType&quot;: &quot;address&quot;,<br>      &quot;name&quot;: &quot;to&quot;,<br>      &quot;type&quot;: &quot;address&quot;<br>    },<br>    {<br>      &quot;indexed&quot;: true,<br>      &quot;internalType&quot;: &quot;uint256&quot;,<br>      &quot;name&quot;: &quot;tokenId&quot;,<br>      &quot;type&quot;: &quot;uint256&quot;<br>    }<br>  ],<br>  &quot;name&quot;: &quot;Transfer&quot;,<br>  &quot;type&quot;: &quot;event&quot;<br>}</pre><p>And that <em>Transfer</em> event takes three input arguments of types “address”, “address”, and “uint256” respectively.</p><p>Please note that each of these arguments have <strong>indexed</strong> set to <strong>true</strong> which means that the values will be part of the <strong>topics</strong> array.</p><p>In other words:</p><ul><li><strong>topics[0] </strong>=<strong> event signature hash</strong></li><li><strong>topics[1]</strong> = <strong>from (address)</strong></li><li><strong>topics[2] </strong>=<strong> to (address)</strong></li><li><strong>topics[3]</strong> = <strong>tokenId (uint256)</strong></li></ul><p>How can<strong> </strong>we verify how<strong> topics[0]</strong> was calculated?</p><pre>echo -n &quot;Transfer(address,address,uint256)&quot; | keccak-256sum -<br>ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef  -</pre><p>The hash matches!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*c9sQcWo6sckjpGqheJMyNQ.jpeg" /></figure><h3>Filtering Logs</h3><p>Alright, so all we need now is a filtering primitive to weed out (drum roll please!) all the transactions on-chain except for the ones involving Murakami Flowers <em>T</em>ransfer events.</p><p>In other words, we want to find any event log with an <strong>address = 0x7D882…</strong> <strong>and topic[0] = 0xddf25… </strong>which again, represents a <em>Transfer </em>event from the Murakami Flowers smart contract.</p><p>Luckily, the JSON-RPC spec has two main methods for filtering out logs.</p><p>In this article, we are going to implement the one version via the <a href="https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs"><strong>eth_getLogs</strong></a><strong> </strong>JSON-RPC. It takes four arguments:</p><ul><li><strong>fromBlock</strong>: The beginning block to scan, “0x0” or <strong>earliest</strong> for <strong>genesis</strong></li><li><strong>toBlock</strong>: The last block to scan, <strong>latest </strong>can be used for the current <strong>block height</strong></li><li><strong>address</strong>: A list of contract addresses of interest</li><li><strong>topics</strong>: A filter that allows us to match log entries</li><li><strong>blockHash</strong>: future field we don’t have to worry about</li></ul><p>Let’s just take a look at the last 10000 blocks from our current <strong>block height</strong></p><pre>$ curl -s -X POST  -H &#39;Content-Type: application/json&#39; \<br>  &quot;http://localhost:8545&quot; \<br>  --data &#39;{&quot;id&quot;: 1, &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;method&quot;: &quot;eth_getLogs&quot;, &quot;params&quot;: [{ &quot;fromBlock&quot;: &quot;0x103C762&quot;, &quot;toBlock&quot;: &quot;0x103EE72&quot;, &quot;address&quot;: [&quot;0x7D8820FA92EB1584636f4F5b8515B5476B75171a&quot;], &quot;topics&quot;: [&quot;0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef&quot;]}]}&#39;<br>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;result&quot;: [<br>    {<br>      &quot;address&quot;: &quot;0x7d8820fa92eb1584636f4f5b8515b5476b75171a&quot;,<br>      &quot;topics&quot;: [<br>        &quot;0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31&quot;,<br>        &quot;0x00000000000000000000000042c160eada4a2f1bebb14d40aed8c54883bc1a22&quot;,<br>        &quot;0x0000000000000000000000001e0049783f008a0085193e00003d00cd54003c71&quot;<br>      ],<br>      &quot;data&quot;: &quot;0x0000000000000000000000000000000000000000000000000000000000000001&quot;,<br>      &quot;blockNumber&quot;: &quot;0x103c76e&quot;,<br>      &quot;transactionHash&quot;: &quot;0x04e1de00143f59a0036e2fa00e3f7966346f9abefd710ac8aefd08636e19c72a&quot;,<br>      &quot;transactionIndex&quot;: &quot;0x4&quot;,<br>      &quot;blockHash&quot;: &quot;0x61a58e94d17a2505ec8c760becc186915baa9244759b0a36088549e5229418a0&quot;,<br>      &quot;logIndex&quot;: &quot;0x3&quot;,<br>      &quot;removed&quot;: false<br>    },<br>...</pre><p>Eureka! We found some!</p><p>Now we can set the <strong>fromBlock</strong> to <strong>earliest </strong>and the <strong>toBlock</strong> to <strong>latest</strong> and do a full chain scan.</p><h3>TL;DR</h3><ul><li>Ethereum has three main data primitives: blocks, transactions, and logs</li><li>Blocks and transactions have mostly low-value data while logs have generally high-value data (for analytics purposes anyway)</li><li>Transactions are initiated by calling into a smart contract</li><li>Smart contracts emit events which generate event log entries</li><li>We can filter for logs using the contract address and the event signature hash using the <strong>eth_getLogs</strong> JSON-RPC call</li></ul><p>In the next article, we’ll talk about ABI translation and how to take the raw logs output above and convert it into something far more palatable (and valuable too).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3af30068e75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/decoding-decentralization-f3af30068e75">Decoding Decentralization</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To Serve Man]]></title>
            <link>https://medium.com/data-science/to-serve-man-60246a82d953?source=rss-e13ebfdd5f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/60246a82d953</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[seldon]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alexander Sack]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 02:00:27 GMT</pubDate>
            <atom:updated>2020-02-24T11:51:09.316Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deploying models on Kubernetes using Seldon Core</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXJ4Xtcc1dfAdWXZjE9K2Q.jpeg" /><figcaption>Source: Pixabay</figcaption></figure><h3>Introduction</h3><p>One of the very best papers ever written about machine learning ironically had very little to do with, well, actual machine learning!</p><p>In the paper, <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=11&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjBoYzg-8DnAhWIl-AKHfQ2AOEQFjAKegQIAxAB&amp;url=https%3A%2F%2Fpapers.nips.cc%2Fpaper%2F5656-hidden-technical-debt-in-machine-learning-systems&amp;usg=AOvVaw3pwxPSkCQaevZTdxkTOe0G">Hidden Technical Debt in Machine Learning Systems,</a> a group of machine learning researchers from Google astutely pointed out that “only a small fraction of any real-world ML system is composed of ML code” and that typically “the required surrounding infrastructure [of the model] is vast and complex.”</p><p>In other words, being able to transition a model from a single cell in a Jupyter notebook to a piece of actual production software is not easy.</p><h3>Serving Infrastructure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTn8k4eIA2c50XWIHulFNg.jpeg" /></figure><p>As the paper’s diagram illustrates above, one of the bigger pieces of any production ML system is its serving infrastructure, which is typically where stakeholders get to actually interact with the ML code.</p><p>And for many enterprises that infrastructure is some sort of container orchestration engine like Kubernetes.</p><p>But before diving into the technical details about how to serve models under Kubernetes using a framework like Seldon Core, <em>why go through all this trouble in the first place?</em></p><h3>Models as First Class Citizens</h3><p>It is much easier to maintain and manage a complex system when it defines and enforces true separation of concerns across its major functional areas.</p><p>Put simply, you want all the machine learning code to be self-contained and not be dependent on the run-time of the broader application in which it is a part of.</p><p>That’s why for example, serving models as self-contained Docker images or burying them within a custom Flask or Shiny application is generally frowned upon in production — it hides the machine learning bits underneath a lot of layers making it harder to manage.</p><p>Ideally, you want to be able to leverage the same deployment and management idioms you use for your other compute resources like CPU, storage, etc. but with your models.</p><p>That way data scientists and/or machine learning engineers can focus on model design and performance while your MLop person can focus on model deployment and the infrastructure around it.</p><p>In the Kubernetes world, that means models should be defined as true Kubernetes objects (<a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/">YAML</a>/<a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/">CRDs</a>) and managed with kubectl.</p><h3>Enter Seldon Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7piKtwfDPgClo1NFBxTEnA.png" /><figcaption>Source: Seldon Core documentation</figcaption></figure><p><strong>Seldon Core</strong> is an open source project that provides a general purpose model serving framework for your Kubernetes cluster. It solves three main challenges:</p><ul><li>Supports a multitude of machine learning frameworks in a number of different languages.</li><li>Exposes models automatically as a REST or gRPC web service.</li><li>Supports full life cycle management of the model deployment including health, telemetry, security, and scaling.</li></ul><p>In this article, we are going to deploy a simple REST style model service under Seldon Core that ingests an image and then returns it unmodified.</p><p>In the process, you will see how easily it is to inject your ML code to perform inference to create a full fledged model microservice.</p><p>By the end of the article, you should have a solid understanding on how to deploy models under Seldon Core on Kubernetes.</p><h3>The Inference Graph</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*sEjkpcJhihD7sKPcGXyQ_w.png" /><figcaption>Source: Seldon Core documentation</figcaption></figure><p>Seldon Core’s prediction API has you define your model as an <strong>inference graph</strong>.</p><p>Requests flow through each node of the graph eventually hitting a <strong>Model</strong> leaf node that runs some kind of prediction function in your favorite ML framework (e.g. Tensorflow, scikit-learn) and returns the result.</p><p><a href="https://docs.seldon.io/projects/seldon-core/en/latest/reference/apis/internal-api.html">Seldon Core supports a number of different kinds of nodes</a> that allows you to create more complex inference graph workflows as the diagram above demonstrates.</p><p>The simplest inference graph though is one with just a single root Model<strong> </strong>node, which is what our example service will implement.</p><h3>Prerequisites</h3><p>The following assumptions are being made when walking through the below tutorial:</p><ul><li>You have access to a Kubernetes cluster (≥1.12) that has Seldon Core already installed on it or have administrative access to a cluster in order to install it.</li></ul><p>Seldon Core is easy to install: <a href="https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html">Just follow a few simple instructions to deploy it</a>.</p><ul><li>You have Docker installed and are comfortable writing Dockerfiles as well as building and pushing images to your local cluster registry.</li></ul><h3>Pick a language, any language…</h3><p>Currently, <a href="https://docs.seldon.io/projects/seldon-core/en/latest/wrappers/README.html">Seldon Core supports a multitude of languages</a> including Python, R, Java, NodeJS, and now Go (alpha).</p><p>But <em>how</em>?</p><p>The fundamental unit of execution in any k8s cluster is a Pod, which is always backed by one or more Docker containers.</p><p>Seldon Core has you first implement your model code under their prediction API and then wrap it within a Docker container.</p><p>The image you create can either be built via a <strong>Dockerfile</strong> directly or using <a href="https://github.com/openshift/source-to-image">OpenShift’s s2i tool</a> with Seldon Core’s wrapper images as a base.</p><p>For our simple Python based service example, we will create it directly using a few simple Dockerfile directives.</p><h3>At Your Service</h3><p>Alright, let’s code up a simple Python service we can deploy under Seldon Core using its prediction API.</p><p>Our service is simply going to read in an image as a tensor and then return it.</p><p>Create a file called <strong>MyModel.py</strong> as follows<strong>:</strong></p><pre>#!/usr/bin/env python3</pre><pre>import io<br>import logging<br>import numpy as np</pre><pre>from PIL import Image</pre><pre>logger = logging.getLogger(&#39;__mymodel__&#39;)</pre><pre><strong>class MyModel(object):</strong></pre><pre>  def __init__(self):</pre><pre>    logger.info(&quot;initializing...&quot;)<br>    logger.info(&quot;load model here...&quot;)<br>    self._model = None<br>    logger.info(&quot;model has been loaded and initialized...&quot;)</pre><pre>  <strong>def predict(self, X, features_names):<br>    </strong>&quot;&quot;&quot; Seldon Core Prediction API &quot;&quot;&quot;<br> <br>    logger.info(&quot;predict called...&quot;)</pre><pre>    # Use Pillow to convert to an RGB image then reverse channels.<br>    logger.info(&#39;converting tensor to image&#39;)<br>    <strong>img = Image.open(io.BytesIO(X)).convert(&#39;RGB&#39;)<br>    img = np.array(img)<br>    img = img[:,:,::-1]</strong></pre><pre>    logger.info(&quot;image size = {}&quot;.format(img.shape))</pre><pre>    if self._model:<br>      logger.info(&quot;perform inference here...&quot;)</pre><pre>    # This will serialize the image into a JSON tensor<br>    logger.info(&quot;returning prediction...&quot;)</pre><pre>    # Return the original image sent in RGB<br>    <strong>return img[:,:,::-1]</strong></pre><p>Let’s break it down:</p><ul><li>Our model service class is a simple Python object that implements a <strong>predict()</strong> method. Notice that no Seldon Core API is needed within your actual model code. All you need to do is create a class object with a predict() method and you’re done!</li><li>The predict() method takes as input a <strong>tensor X</strong> and a list of <strong>feature_names</strong>. These types are defined by the Seldon Core protobuf specification found <a href="https://docs.seldon.io/projects/seldon-core/en/latest/reference/apis/prediction.html#proto-buffer-and-grpc-definition">here</a>. In our example service, we are only going to use the tensor object since our model ingests images.</li><li>We need to convert the byte array like object X passed in by Seldon Core to an RGB image.</li><li>We then reverse the image’s channels to create our final BGR image for processing (suitable for say some <a href="https://opencv.org/">OpenCV</a> processing).</li><li>Notice that we can inject loading the model on class instantiation and then run inference within the predict() function very easily.</li></ul><h3>Wrap It Up!</h3><p>Now that we have our model class is sorted out, let’s use this code to build a Docker container using the Seldon Core wrapper APIs.</p><p>Create a <strong>Dockerfile</strong> that looks like:</p><pre>FROM python:3.7-buster</pre><pre>RUN apt-get update &amp;&amp; DEBIAN_FRONTEND=noninteractive &amp;&amp; apt-get install -y \<br>   curl \<br>   python3-setuptools &amp;&amp; \<br>apt-get clean &amp;&amp; apt-get autoremove -y &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><pre>COPY requirements.txt .<br>RUN curl -s <a href="https://bootstrap.pypa.io/get-pip.py">https://bootstrap.pypa.io/get-pip.py</a> -o get-pip.py &amp;&amp; python3 get-pip.py &amp;&amp; rm -f get-pip.py</pre><pre>RUN pip3 install --no-cache numpy Pillow <strong>seldon-core</strong></pre><pre><strong># Seldon Core specific</strong><br><strong>COPY . /microservice<br>WORKDIR /microservice</strong></pre><pre><strong>ENV MODEL_NAME MyModel<br>ENV API_TYPE REST<br>ENV SERVICE_TYPE MODEL<br>ENV PERSISTENCE 0</strong></pre><pre><strong>CMD exec seldon-core-microservice $MODEL_NAME $API_TYPE --service-type $SERVICE_TYPE --persistence $PERSISTENCE</strong></pre><pre><strong>EXPOSE 5000</strong></pre><p>Let’s break it down:</p><ul><li>Most of the Dockerfile is pretty standard fare as we create a small Python 3.7 buster image with a few run-time requirements.</li><li>Notice we install the <strong>seldon-core</strong> Python module as part of our model run-time.</li><li>We install our application in the <strong>/microservice</strong> directory of the container.</li><li>Your model class object is actually loaded by the <strong>seldon-core-microservice </strong>application and exposes it as a <a href="https://flask.palletsprojects.com/">Flask</a> webapp internally (we’ll realize that when we actually deploy the model).</li><li>Seldon Core supports both REST and gRPC web service APIs. Here we specify REST since we are going to test our service using a simple http POST operation.</li></ul><p>Build the image and push it to your cluster’s repository:</p><pre>$ docker build --no-cache -t my-model:0.1 .<br>Sending build context to Docker daemon  6.144kB<br>Step 1/14 : FROM python:3.7-buster<br>---&gt; 879165535a54<br>...<br>Step 14/14 : EXPOSE 5000<br> ---&gt; Running in 8e9f588abe89<br> ---&gt; 83b0a4682783<br>Successfully built 83b0a4682783</pre><pre>$ docker tag my-model:latest &lt;your repo&gt;/my-model:0.1<br>$ docker push &lt;your repo&gt;/my-model:0.1</pre><h3>Serve Local</h3><p>Now that we have an image built, let’s test it by running our <strong>seldon-core-microservice</strong> as a stand alone docker container:</p><pre>$ docker run -d --rm --name my-model -p 5000:5000 my-model:0.1<br>5aa997b0b093612f88499e13260cf96ee6d9931749f2dfa23ee3d61d303c2cc5<br>$ docker logs -f my-model<br>2020-02-21 01:49:38,651 - seldon_core.microservice:main:190 - INFO:  Starting microservice.py:main<br>...<br><strong>2020-02-21 01:49:38,659 - __mymodel__:__init__:15 - INFO:  initializing...<br>2020-02-21 01:49:38,659 - __mymodel__:__init__:16 - INFO:  load model here...<br>2020-02-21 01:49:38,659 - __mymodel__:__init__:18 - INFO:  model has been loaded and initialized...</strong><br>2020-02-21 01:49:38,659 - seldon_core.microservice:main:325 - INFO:  REST microservice running on <strong>port 5000</strong><br>2020-02-21 01:49:38,659 - seldon_core.microservice:main:369 - INFO:  Starting servers<br> * Serving Flask app &quot;seldon_core.wrapper&quot; (lazy loading)<br> * Environment: production<br>   WARNING: This is a development server. Do not use it in a production deployment.<br>   Use a production WSGI server instead.<br> * Debug mode: off<br>2020-02-21 01:49:38,673 - werkzeug:_log:113 - INFO:   * Running on <a href="http://0.0.0.0:5000/">http://0.0.0.0:5000/</a> (Press CTRL+C to quit)</pre><p>Notice that the MyModel class you wrote above got loaded and is being served up as a Flask application on port 5000. The model’s prediction endpoint is at<strong> ‘/predict’</strong> or <strong>‘/api/v0.1/predictions’</strong>.</p><h3>Shop Local</h3><p>Let’s test our MyModel service by writing a simple client script that will POST an image file to our model’s predict endpoint. We will use this same script to test our deployment lon Kubernetes by just changing the URL.</p><p>Here is our client, <strong>my-model-client.py</strong>:</p><pre>#!/usr/bin/env python3</pre><pre>import base64<br>import json<br>import logging<br>import os<br>import numpy as np<br>import requests<br>import sys</pre><pre>from PIL import Image</pre><pre>logger = logging.getLogger(&#39;__mymodelclient__&#39;)<br>logger.setLevel(logging.INFO)<br>logger.addHandler(logging.StreamHandler())</pre><pre>if __name__ == &#39;__main__&#39;:<br>    url = sys.argv[1]<br>    path = sys.argv[2]</pre><pre>    <strong># base64 encode image for HTTP POST<br>    data = {}<br>    with open(path, &#39;rb&#39;) as f:<br>        data[&#39;binData&#39;] = base64.b64encode(f.read()).decode(&#39;utf-8&#39;)</strong></pre><pre>    logger.info(&quot;sending image {} to {}&quot;.format(path, url))<br>  <strong>  response = requests.post(url, json = data, timeout = None)</strong><br>    <br>    logger.info(&quot;caught response {}&quot;.format(response))<br>    status_code = response.status_code<br>    js = response.json()</pre><pre>    if response.status_code == requests.codes[&#39;ok&#39;]:<br>        logger.info(&#39;converting tensor to image&#39;)<br>        data = js.get(&#39;data&#39;)<br>        tensor = data.get(&#39;tensor&#39;)<br>        shape = tensor.get(&#39;shape&#39;)<br>        values = tensor.get(&#39;values&#39;)<br>        logger.info(&quot;output image shape = {}&quot;.format(shape))</pre><pre>        # Convert Seldon tensor to image<br>       <strong> img_bytes = np.asarray(values)<br>        img = img_bytes.reshape(shape)<br>        Image.fromarray(img.astype(np.uint8)).save(&#39;result.jpg&#39;)</strong><br>        logger.info(&#39;wrote result image to result.jpg&#39;)<br>    elif response.status_code == requests.codes[&#39;service_unavailable&#39;]:<br>        logger.error(&#39;Model service is not available.&#39;)<br>    elif response.status_code == requests.codes[&#39;internal_server_error&#39;]:<br>        logger.error(&#39;Internal model error.&#39;)</pre><p>Let’s break it down:</p><ul><li>We pass the URL we want to post the image to and the path to the image itself.</li><li>We need to base64 encode the image in preparation for the POST to our Seldon Core microservice running locally as a container.</li><li>We send a POST with a JSON string that contains the <strong>binData</strong> key and the base64 encoded image as its value.</li><li>If the POST was successful (HTTP STATUS OK 200) we read the <strong>data</strong> key from the JSON response and extract the <strong>tensor</strong> which is really our resultant image.</li><li>The tensor has both a <strong>shape</strong> and <strong>values </strong>key — the values key is the image itself as an array of pixel intensities.</li><li>We use <strong>Pillow</strong> to write out the tensor values as a JPEG file called ‘result.jpg’.</li></ul><p>Let’s test our service now using this script:</p><pre>$ file test_image.jpg<br>test_image.jpg: JPEG image data, JFIF standard 1.00, resolution (DPI), density 0x0, segment length 16, comment: &quot;LEAD Technologies Inc. V1.01&quot;, baseline, precision 8, <strong>1280x960, components 3</strong></pre><pre>$ python3 my-model-client.py <a href="http://localhost:5000/api/v0.1/predictions">http://localhost:5000/api/v0.1/predictions</a> test_image.jpg<br>sending image test_image.jpg to <a href="http://localhost:5000/api/v0.1/predictions">http://localhost:5000/api/v0.1/predictions</a><br>caught response &lt;Response [200]&gt;<br>converting tensor to image<br>result image shape = [960, 1280, 3]<br>wrote result image to result.jpg</pre><pre>$ file result.jpg<br>result.jpg: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, baseline, precision 8, <strong>1280x960, components 3</strong></pre><p>Let’s also see the log messages of the docker container that processed the image:</p><pre>$ docker logs my-model<br>2020-02-21 15:32:33,363 - __mymodel__:predict:22 - <strong>INFO:  predict called...</strong><br>2020-02-21 15:32:33,391 - __mymodel__:predict:27 - <strong>INFO:  image size = (960, 1280, 3)</strong><br>2020-02-21 15:32:33,391 - __mymodel__:predict:33 - <strong>INFO:  returning prediction...</strong><br>2020-02-21 15:32:33,977 - seldon_core.user_model:client_class_names:166 - INFO:  class_names is not implemented<br>2020-02-21 15:32:33,977 - seldon_core.user_model:client_custom_tags:134 - INFO:  custom_tags is not implemented<br>2020-02-21 15:32:33,977 - seldon_core.user_model:client_custom_tags:134 - INFO:  custom_tags is not implemented<br>2020-02-21 15:32:33,977 - seldon_core.user_model:client_custom_metrics:307 - INFO:  custom_metrics is not implemented<br>2020-02-21 15:32:34,271 - werkzeug:_log:113 - INFO:  172.17.0.1 - - [21/Feb/2020 15:32:34] <strong>&quot;POST /api/v0.1/predictions HTTP/1.1&quot; 200 -</strong></pre><h3>Deploy It!</h3><p>Like all things Kubernetes, Seldon Core defines its own Deployment object called a <strong>SeldonDeployment </strong>via a <strong>Custom Resource Definition (CRD)</strong> file.</p><p>Let’s define our model’s SeldonDeployment via a <strong>seldon-deploy.yaml </strong>file:</p><pre>apiVersion: machinelearning.seldon.io/v1alpha2<br>kind: SeldonDeployment<br>metadata:<br>  name: my-model<br>spec:<br>  name: my-deployment<br>  <strong>predictors:</strong><br>  - componentSpecs:<br>    - spec:<br>        containers:<br>        - name: my-model-graph<br>          image: &lt;your cluster&#39;s registry&gt;/my-model:0.1<br>    <strong>graph:</strong><br>      <strong>children: []</strong><br>      <strong>endpoint:<br>        type: REST<br>      name: classifier</strong><br>      <strong>type: MODEL<br>    annotations:<br>      predictor_version: &quot;0.1&quot;<br>      seldon.io/svc-name: my-model-svc   </strong> <br>    <strong>name: my-graph</strong><br> <strong>   replicas: 1</strong></pre><p>Let’s break it down:</p><ul><li>A SeldonDeployment consists of one or more <strong>predictors</strong> which defines what models are contained within this deployment. Note: You may want to define more than one predictor for canary or multi-arm bandit type scenarios.</li><li>Every predictor consists of a <strong>Pod spec</strong> that defines the Docker image of your model code which we built above.</li><li>Since a SeldonDeployment is a type of Deployment, each predictor is backed by one or more <strong>ReplicaSets</strong> which defines how many Pods should be created to back your model (inference graph). This is one of the ways that allows you to scale your SeldonDeployment to meet your compute needs.</li><li>We also set a custom service name since a SeldonDeployment which will auto-expose our microservice as Kubernetes <strong>Service</strong> object.</li></ul><p>Let’s create the SeldonDeployment and look at deployment as well as the objects behind that get created:</p><pre>$ kubectl get seldondeployments<br>NAME       AGE<br>my-model   6s</pre><pre>$ kubectl create -f seldon-deploy.yaml<br>seldondeployment.machinelearning.seldon.io/my-model created</pre><pre>$ kubectl get all<br>NAME                                                  READY   STATUS    RESTARTS   AGE<br><strong>pod/my-deployment-my-graph-20302ae-5cfc6c47f4-m78ll</strong>   2/2     Running   0          80s</pre><pre>NAME                                              TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)             AGE<br><strong>service/my-model-svc</strong>                              ClusterIP   172.26.126.119   &lt;none&gt;        8000/TCP,5001/TCP   55s<br>service/seldon-9d8927429acc983eba0168e21059f589   ClusterIP   172.28.210.215   &lt;none&gt;        9000/TCP            80s</pre><pre>NAME                                             READY   UP-TO-DATE   AVAILABLE   AGE<br><strong>deployment.apps/my-deployment-my-graph-20302ae</strong>   1/1     1            1           80s</pre><pre>NAME                                                        DESIRED   CURRENT   READY   AGE<br>replicaset.apps/my-deployment-my-graph-20302ae-5cfc6c47f4   1         1         1       80s</pre><p>Notice a few things:</p><ul><li>The Pod created that runs your model code has actually two containers in it — your model’s code as well as the “sidecar” <strong>seldon-container-engine</strong> which is injected at deployment time.</li><li>The <strong>seldon-container-engine</strong> will marshal all requests and responses into the Seldon Core message format as well as monitor your model container’s health and telemetry.</li><li>A ClusterIP service is exposed on port 8000 for us to communicate with our microservice.</li></ul><p>Now that our model microservice is up and running, let’s test it using the same client above. We need to either setup a publicly accessible <strong>Ingress</strong> or use <strong>port-forwarding </strong>to create a direct connection to our Service object.</p><p>In our simple example, let’s just use a simple port-forward:</p><pre>$ kubectl port-forward svc/my-model-svc 8000:8000<br>Forwarding from 127.0.0.1:8000 -&gt; 8000<br>Forwarding from [::1]:8000 -&gt; 8000<br>Handling connection for 8000</pre><pre>$ python3 my-model-client.py <a href="http://localhost:8000/api/v0.1/predictions">http://localhost:8000/api/v0.1/predictions</a> test_image.jpg<br>sending image test_image.jpg to <a href="http://localhost:8000/api/v0.1/predictions">http://localhost:8000/api/v0.1/predictions</a><br>caught response &lt;Response [200]&gt;<br>converting tensor to image<br>result image shape = [960, 1280, 3]<br>wrote result image to result.jpg</pre><p>Success!</p><p>We just sent an image for inference and got a response back from our microservice running on our cluster.</p><p>You can now open up your original image and the result one returned by our microservice and it should look the same.</p><p>To verify we can even dump the logs within the Pod itself:</p><pre>$ kubectl logs deployment.apps/my-deployment-my-graph-20302ae -c my-model-graph<br>...<br>2020-02-22 01:44:49,163 - __mymodel__:predict:22 - INFO:  predict called...<br>2020-02-22 01:44:49,223 - __mymodel__:predict:27 - INFO:  image size = (960, 1280, 3)<br>2020-02-22 01:44:49,223 - __mymodel__:predict:33 - INFO:  returning prediction...<br>2020-02-22 01:44:49,948 - seldon_core.user_model:client_class_names:166 - INFO:  class_names is not implemented<br>2020-02-22 01:44:49,949 - seldon_core.user_model:client_custom_tags:134 - INFO:  custom_tags is not implemented<br>2020-02-22 01:44:49,949 - seldon_core.user_model:client_custom_tags:134 - INFO:  custom_tags is not implemented<br>2020-02-22 01:44:49,949 - seldon_core.user_model:client_custom_metrics:307 - INFO:  custom_metrics is not implemented<br>2020-02-22 01:44:50,355 - werkzeug:_log:113 - INFO:  127.0.0.1 - - [22/Feb/2020 01:44:50] &quot;POST /predict HTTP/1.1&quot; 200 -</pre><h3>Clean Up</h3><pre>$ kubectl delete -f seldon-deploy.yaml<br>seldondeployment.machinelearning.seldon.io &quot;my-model&quot; deleted</pre><p>Our SeldonDeployment and associated objects are all now terminated.</p><h3>Conclusion</h3><p>I hope by going through this short tutorial you have a deeper understanding of how to use Seldon Core to deploy your models as microservices under Kubernetes.</p><p>In general, the Seldon Core development workflow is as follows:</p><ul><li>Code your inference graph as a simple set of Python objects following the Seldon Core prediction API.</li><li>Wrap your model code and run-time as a Docker container.</li><li>Test your container locally first to verify that your model code works as expected.</li><li>Deploy your model as a microservice as a SeldonDeployment object.</li><li>Test your SeldonDeployment microservice by either creating an Ingress or using port-forwarding to push requests to it.</li></ul><p>Seldon Core supports many advanced features that I did not touch upon within this article so I encourage you to really peruse the project’s <a href="https://docs.seldon.io/projects/seldon-core/en/latest/">extensive documentation</a> to better understand its overall design and vast feature set.</p><p>But hopefully, this article gave you just enough of a taste to pique your interest in why a dedicated serving infrastructure like Seldon Core is well worth your time and energy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60246a82d953" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/to-serve-man-60246a82d953">To Serve Man</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ignite the Spark!]]></title>
            <link>https://medium.com/data-science/ignite-the-spark-68f3f988f642?source=rss-e13ebfdd5f62------2</link>
            <guid isPermaLink="false">https://medium.com/p/68f3f988f642</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Alexander Sack]]></dc:creator>
            <pubDate>Fri, 07 Feb 2020 03:47:50 GMT</pubDate>
            <atom:updated>2020-04-28T22:30:58.099Z</atom:updated>
            <content:encoded><![CDATA[<h4>Running Apache Spark on Kubernetes using PySpark</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gj_mxMOlCQ3vgIjnDKeY-Q.jpeg" /><figcaption>Source: Free-Photos from Pixabay</figcaption></figure><h3><strong>Introduction</strong></h3><p>In this primer, you are first going to learn a little about how Apache Spark’s cluster manager works and then how you can run PySpark within a Jupyter notebook interactively on an existing Kubernetes (k8s) cluster.</p><p>After completing this article, you should be able to develop Spark applications on any Kubernetes cluster with confidence as well as have a deeper understanding of how the two are wired together.</p><h3>It’s all about context</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*EzZs4uEuO30lV51KV07_RA.png" /><figcaption>Source: Apache Documentation</figcaption></figure><p>Spark is a fast and general-purpose <strong>cluster computing system</strong><em> </em>which means by definition compute is shared across a number of interconnected nodes in a distributed fashion.</p><p>But how does Spark actually distribute a given workload across a cluster?</p><p>Spark adopts a Master/Slave approach whereby a <strong>driver program</strong> (“the master”) creates a <strong>SparkContext</strong> object that connects to<strong> </strong>a <strong>cluster manager</strong>.</p><p>The SparkContext created (either programmatically by your favorite language binding or on your behalf when you submit a job) abstracts the cluster as one large compute node that your application uses to perform work.</p><p>The <strong>cluster manager</strong> on the other hand, is responsible for spawning and managing a number of <strong>worker nodes</strong> (“the slaves”) that each run an <strong>executor process </strong>on behalf of the SparkContext to do the actual work.</p><p>When data in the form of a <strong>Resilient Distributed Dataframe (RDD)</strong> is manipulated by your Spark application, the RDD is split into a number of partitions and distributed across these worker node/executor combinations for processing. The final result is aggregated across the nodes and sent back to the driver.</p><h3>Pick a manager, any cluster manager</h3><p>One of the key advantages of this design is that the cluster manager is decoupled from your application and thus interchangeable.</p><p>Traditionally, Spark supported three types of cluster managers:</p><ul><li><strong>Standalone</strong></li><li><strong>Apache Mesos</strong></li><li><strong>Hadoop YARN</strong></li></ul><p>The <a href="https://spark.apache.org/docs/latest/spark-standalone.html">Standalone</a> cluster manager is the default one and is shipped with every version of Spark. It is a no frills, competent manager that is meant to get you up and running as fast as possible.</p><p><a href="https://spark.apache.org/docs/latest/running-on-mesos.html">Apache Mesos</a> is a clustering technology in its own right and meant to abstract away all of your cluster’s resources as if it was one big computer. Mesos ships with a cluster manager that you can leverage with Spark.</p><p><a href="https://spark.apache.org/docs/latest/running-on-yarn.html">Hadoop YARN</a> (“Yet Another Resource Negotiator”) was developed as an outgrowth of the Apache Hadoop project and mainly focused on distributing MapReduce workloads. As a result, it too is a cluster manager which Spark can talk to natively.</p><h3>Enter Kubernetes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*tkWi16Clt_6RjLJNmyLVkg.png" /><figcaption>Source: Apache Documentation</figcaption></figure><p>As of 2.3.0, Spark now supports using Kubernetes directly as a cluster manager.</p><p>But what does that <em>really</em> mean?</p><p>That depends based on how you want to run Spark on Kubernetes.</p><p>In <strong>cluster mode</strong>, after you submit an application using <strong>spark-submit</strong>, the SparkContext created on behalf of your application will ask the <strong>kube-apiserver</strong> to setup a driver node and a number of corresponding worker nodes (Pods) and proceed to run your workload on top of them.</p><p>Once all the data processing has finished, on tear down, the ephemeral worker node Pods will be terminated automatically but the driver node Pod will remain so you can inspect any logs before manually deleting it.</p><p>In <strong>client mode</strong>, you create the Spark driver node as a Pod then create a SparkContext using your favorite language’s API bindings before finally submitting work.</p><p>This primer is going to focus on configuring client mode for a few reasons:</p><ul><li>The majority of documentation available on the web is in cluster mode</li><li>The steps to submit an application using spark-submit are not that different than using the existing cluster managers</li><li>Most Spark developers will want to use client mode so they can develop new applications and explore data interactively</li></ul><h3>Prerequisites</h3><p>The below instructions assume the following:</p><ul><li>You have administrative access to either a Kubernetes cluster or to a dedicated namespace within that cluster</li></ul><p>I’m running a small 1.17.2 eight node cluster that was setup using the <a href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/">kubeadm</a> tool. I believe any cluster 1.15+ should work just fine.</p><p>If you don’t have a cluster to work with, I highly suggest installing <a href="https://kubernetes.io/docs/tasks/tools/install-minikube/">MiniKube</a> on your desktop as a way to follow along.</p><ul><li>You are somewhat familiar with Kubernetes core concepts such as Pods, Deployments, and Services</li><li>You have Docker installed, understand the concept behind containers, and are comfortable building a custom image using a Dockerfile</li><li>You have access to a Docker registry either on-premise, in-cloud, or off-premise such as <a href="https://hub.docker.com/">Docker Hub</a>.</li><li>You are using the latest stable release of Spark which is v2.4.4 at the time of this writing</li></ul><h3>Cluster Setup</h3><p>Before we start building images and deploying Pods, let’s setup a dedicated namespace where our combo Jupyter notebook/Spark driver node will be deployed as well as all of its corresponding worker nodes.</p><pre>$ kubectl create namespace spark<br>namespace/spark created</pre><p>In order for your driver Pod to request resources from the cluster it has to use some kind of <strong>ServiceAccount</strong> that has the right <strong>Role Base Access Control (RBAC)</strong>.</p><p>The Spark documentation suggests creating a <strong>RoleBinding</strong> or a <strong>ClusterRoleBinding</strong> to accomplish this. Which method you choose to implement is entirely based on the security policy of your cluster.</p><p>For this example, we will create a ServiceAccount called <strong>spark</strong> in the <strong>spark namespace</strong><em> </em>with a ClusterRoleBinding that gives this account the right permissions:</p><pre>$ kubectl create serviceaccount spark -n spark<br>serviceaccount/spark created</pre><pre>$ kubectl create clusterrolebinding spark-role --clusterrole=edit --serviceaccount=spark:spark --namespace=spark<br>clusterrolebinding.rbac.authorization.k8s.io/spark-role created</pre><h3>Docker Setup</h3><p>As per above, since every worker node is really just a Pod on our cluster, we will need a docker image with the correct Spark run-time.</p><p>Fortunately, the Spark team provides a bunch of <strong>Dockerfiles</strong> and a tool (<strong>docker-image-tool.sh</strong>) to create images with them that are ready to be deployed on any Kubernetes cluster.</p><p>Each Dockerfile is meant to be used with the three major language bindings Spark supports — Scala, Python, and R.</p><p>Let’s build the default images so we have at least some base image to work with:</p><pre>$ wget -qO- <a href="http://mirrors.gigenet.com/apache/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz">http://mirrors.gigenet.com/apache/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz</a> | tar -xzf -</pre><pre>$ cd spark-2.4.4-bin-hadoop2.7 &amp;&amp; bin/docker-image-tool.sh build<br>Sending build context to Docker daemon  262.2MB<br>...<br>Successfully built 02fb36ac3ee0<br>Successfully tagged spark:latest<br>Sending build context to Docker daemon  262.2MB<br>...<br>Successfully built 0d33be47d094<br>Successfully tagged spark-py:latest<br>Sending build context to Docker daemon  262.2MB<br>...<br>Successfully built dc911ac3678e<br>Successfully tagged spark-r:latest</pre><p>After the docker-image-tool.sh script completes, you should have three new images ready for deployment on your Kubernetes cluster:</p><pre>$ docker images spark:latest<br>REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE<br>spark               latest              02fb36ac3ee0        7 days ago          344MB</pre><pre>$ docker images spark-py:latest<br>REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE<br>spark-py            latest              0d33be47d094        7 days ago          432MB</pre><pre>$ $ docker images spark-r:latest<br>REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE<br>spark-r             latest              dc911ac3678e        7 days ago          539MB</pre><p>Since this tutorial is going to focus on using PySpark, we are going to use the <strong>spark-py</strong> image for our worker Pod. Normally, you would just push these images to whatever docker registry your cluster uses. However, we are going to create custom versions of them in order to work around a bug.</p><h3>Communication Breakdown</h3><p>At the time of this writing, there is an issue with using the existing Spark v2.4.4 Kubernetes client jar files with newer clusters due to a security CVE that was patched recently.</p><p>You can read more about the issue <a href="https://github.com/kubernetes/kubernetes/issues/82131">here</a> and <a href="https://stackoverflow.com/questions/57643079/kubernetes-watchconnectionmanager-exec-failure-http-403">here</a>.</p><p>The workaround is to build a Spark enabled docker image but with newer client jar files in it.</p><p>Let’s use the base images we just built to do exactly that. Since we are focused on using PySpark, we will only rebuild the spark-py image but the same steps apply to all of them.</p><pre>$ mkdir my-spark-py &amp;&amp; cd my-spark-py</pre><pre>$ wget -qO- <a href="http://apache.mirrors.hoobly.com/spark/spark-3.0.0-preview2/spark-3.0.0-preview2-bin-hadoop2.7.tgz">http://apache.mirrors.hoobly.com/spark/spark-3.0.0-preview2/spark-3.0.0-preview2-bin-hadoop2.7.tgz</a> | tar -xzf -</pre><pre>$ cp spark-3.0.0-preview2-bin-hadoop2.7/jars/kubernetes*jar . &amp;&amp; rm -f <a href="http://apache.mirrors.hoobly.com/spark/spark-3.0.0-preview2/spark-3.0.0-preview2-bin-hadoop2.7.tgz">spark-3.0.0-preview2/spark-3.0.0-preview2-bin-hadoop2.7.tgz</a></pre><pre>$ cat &lt;&lt; EOF &gt; Dockerfile<br>FROM spark-py:v2.4.4</pre><pre>COPY *.jar /opt/spark/jars/<br>RUN rm /opt/spark/jars/kubernetes-*-4.1.2.jar<br>EOF</pre><pre>$ docker build --rm -t my-spark-py:v2.4.4 .<br>...<br>Successfully built 29abceec5cb2<br>Successfully tagged my-spark-py:v2.4.4</pre><p>So now <strong>my-spark-py:v2.4.4</strong> contains the same official Spark run-time but with updated Kubernetes client jar files taken from the v3.0.0-preview2 release.</p><p>This image will be pulled by Kubernetes every time it creates a worker Pod on demand when we generate our SparkContext.</p><h3>Creating the “Driver” Pod Image</h3><p>Since our ultimate goal is to interactively develop a PySpark application on Kubernetes within a Jupyter notebook, that Pod will also act as our “driver” node.</p><p>Consequently, you have two options:</p><ul><li>Use the <a href="https://hub.docker.com/r/jupyter/pyspark-notebook/">official Jupyter PySpark image</a></li><li><a href="https://github.com/pisymbol/docker/blob/master/spark/Dockerfile">Build your own custom image</a></li></ul><p>The official PySpark docker image is a great place to start and I highly recommend it.</p><p>I built a custom docker image that you can find by clicking the link above. I call this image <strong>my-notebook:latest</strong>.</p><p>You should build, tag and push whatever image you ultimately choose to the docker registry that your cluster uses.</p><h3>Setting up your Deployment</h3><p>As is all things Kubernetes, we need to write a YAML file to deploy our driver Pod that will be used to log into Jupyter and create a SparkContext.</p><p>Here is what my deployment looks like:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br><strong>  namespace: spark</strong><br>  name: my-notebook-deployment<br>  labels:<br>    app: my-notebook<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: my-notebook<br>  template:<br>    metadata:<br>      labels:<br>        app: my-notebook<br>    spec:<br>      <strong>serviceAccountName: spark</strong><br>      containers:<br>      - name: my-notebook<br>        image: pidocker-docker-registry.default.svc.cluster.local:5000/my-notebook:latest<br>        ports:<br>          - containerPort: 8888<br>        volumeMounts:<br>          - mountPath: /root/data<br>            name: my-notebook-pv<br>        workingDir: /root<br>        resources:<br>          limits:<br>            memory: 2Gi<br>      volumes:<br>        - name: my-notebook-pv<br>          persistentVolumeClaim:<br>            claimName: my-notebook-pvc<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  namespace: spark<br>  name: my-notebook-deployment<br>spec:<br>  selector:<br>    app: my-notebook<br>  <strong>ports:<br>    - protocol: TCP<br>      port: 29413<br>  clusterIP: None</strong></pre><p>The highlighted text are directives you should pay attention to:</p><ul><li>We want our deployment to live in the <strong>spark</strong> namespace</li><li>We want to set this deployment’s <strong>ServiceAccount</strong> to <strong>spark</strong> which has the ClusterRoleBinding <strong>spark-role</strong> we created above</li><li>We want to expose our deployment as a headless service as per the <a href="https://spark.apache.org/docs/latest/running-on-kubernetes.html#client-mode">Spark client mode documentation</a> by setting the service’s ClusterIP to None. This allows the worker Pods to communicate with the driver Pod via port 29413. The port number you choose can be any valid unused port but I choose 29413 in this example as an homage to <a href="http://blog.brainlounge.de/memoryleaks/getting-started-with-spark-on-kubernetes/">this helpful post</a>.</li></ul><h3>Create the Deployment</h3><p>When you are satisfied with your deployment, create it via:</p><pre>$ kubectl create -f k8s/deploy.yaml<br>deployment.apps/my-notebook-deployment created<br>service/my-notebook-deployment created</pre><p>Check that your deployment is running:</p><pre>$ kubectl get all -n spark<br>NAME                                          READY   STATUS    RESTARTS   AGE<br>pod/my-notebook-deployment-7bf574447c-pdn2q   1/1     Running   0          19s</pre><pre>NAME                             TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)     AGE<br>service/my-notebook-deployment   ClusterIP   None         &lt;none&gt;        29413/TCP   19s</pre><pre>NAME                                     READY   UP-TO-DATE   AVAILABLE   AGE<br>deployment.apps/my-notebook-deployment   1/1     1            1           19s</pre><pre>NAME                                                DESIRED   CURRENT   READY   AGE<br>replicaset.apps/my-notebook-deployment-7bf574447c   1         1         1       19s</pre><p>And now port-forward to 8888 so you can login into Jupyter:</p><pre>$ kubectl port-forward -n spark deployment.apps/my-notebook-deployment 8888:8888<br>Forwarding from 127.0.0.1:8888 -&gt; 8888<br>Forwarding from [::1]:8888 -&gt; 8888</pre><p>Now you should be able to point your favorite browser to <a href="http://localhost:8888/">http://localhost:8888</a> and log into Jupyter (if you used my image as a reference the password is <strong>‘jupyter’ </strong>else you will need to copy/paste the generated auth token displayed in the container’s log file).</p><h3>Light It!</h3><p>Start a new Python3 notebook and type the following in a cell:</p><pre>import os</pre><pre>from pyspark import SparkContext, SparkConf<br>from pyspark.sql import SparkSession</pre><pre># Create Spark config for our Kubernetes based cluster manager<br>sparkConf = SparkConf()<br>sparkConf.setMaster(&quot;<strong>k8s://</strong><a href="https://kubernetes.default.svc.cluster.local/"><strong>https://kubernetes.default.svc.cluster.local:443</strong></a><strong>&quot;</strong>)<br>sparkConf.setAppName(<strong>&quot;spark&quot;</strong>)<br>sparkConf.set(<strong>&quot;spark.kubernetes.container.image&quot;, &quot;pidocker-docker-registry.default.svc.cluster.local:5000/my-spark-py:v2.4.4&quot;</strong>)<br>sparkConf.set(<strong>&quot;spark.kubernetes.namespace&quot;, &quot;spark&quot;</strong>)<br>sparkConf.set(<strong>&quot;spark.executor.instances&quot;, &quot;7&quot;</strong>)<br>sparkConf.set(&quot;spark.executor.cores&quot;, &quot;2&quot;)<br>sparkConf.set(&quot;spark.driver.memory&quot;, &quot;512m&quot;)<br>sparkConf.set(&quot;spark.executor.memory&quot;, &quot;512m&quot;)<br>sparkConf.set(&quot;spark.kubernetes.pyspark.pythonVersion&quot;, &quot;3&quot;)<br>sparkConf.set(<strong>&quot;spark.kubernetes.authenticate.driver.serviceAccountName&quot;, &quot;spark&quot;</strong>)<br>sparkConf.set(<strong>&quot;spark.kubernetes.authenticate.serviceAccountName&quot;, &quot;spark&quot;</strong>)<br>sparkConf.set(<strong>&quot;spark.driver.port&quot;, &quot;29413</strong>&quot;)<br>sparkConf.set(<strong>&quot;spark.driver.host&quot;, &quot;my-notebook-deployment.spark.svc.cluster.local</strong>&quot;)</pre><pre># Initialize our Spark cluster, this will actually<br># generate the worker nodes.<br>spark = SparkSession.builder.config(conf=sparkConf).getOrCreate()<br>sc = spark.sparkContext</pre><p>Let’s break down the Spark config above:</p><ul><li>We set the master URL to “<strong>k8s://</strong><a href="https://kubernetes.default.svc.cluster.local/"><strong>https://kubernetes.default.svc.cluster.local:443</strong></a><strong>&quot; </strong>which tells Spark that our cluster manager is Kubernetes (k8s) and where to find the kube-apiserver to request resources</li><li>We set the application name to <strong>“spark” </strong>which will be prepended to the worker Pod names. Feel free to use whatever name you deem appropriate</li><li>We set the container image to use for the worker Pods to the custom one we built above that has the updated Kubernetes client jar files in it</li><li>We specify that we want all worker nodes to be created in the <strong>spark</strong> namespace</li><li>I set the number of worker nodes to <strong>“7”</strong> since I am on eight node closer (one node is the master, seven are available for work). You need to pick a number that makes sense for your cluster.</li><li>We set the service account names for both the driver and workers to our ServiceAccount wecreated above (<strong>“spark”</strong>)</li><li>Finally, we set the port number to <strong>29413</strong> and the fully qualified domain name of my in-cluster service which specifies to the worker nodes where to contact the driver node.</li></ul><p>After you execute this cell, you should see a number of worker Pods being spawned in the spark namespace.</p><p>Let’s check it:</p><pre>$ kubectl get pods -n spark<br>NAME                                      READY   STATUS    RESTARTS   AGE<br>my-notebook-deployment-7bf574447c-pdn2q   1/1     Running   0          5m6s<br>spark-1581043649282-exec-1                1/1     Running   0          76s<br>spark-1581043651262-exec-2                1/1     Running   0          75s<br>spark-1581043651392-exec-3                1/1     Running   0          75s<br>spark-1581043651510-exec-4                1/1     Running   0          75s<br>spark-1581043651623-exec-5                1/1     Running   0          75s<br>spark-1581043656753-exec-6                1/1     Running   0          70s<br>spark-1581043656875-exec-7                1/1     Running   0          70s</pre><p>You now have an a Spark cluster running on top of Kubernetes waiting for work!</p><p>As is tradition, let’s calculate <a href="https://en.wikipedia.org/wiki/Pi">the number Pi</a> using our cluster in a new cell:</p><pre>from random import random<br>from operator import add</pre><pre>partitions = 7<br>n = 10000000 * partitions</pre><pre>def f(_):<br>    x = random() * 2 - 1<br>    y = random() * 2 - 1<br>    <br>    return 1 if x ** 2 + y ** 2 &lt;= 1 else 0</pre><pre>count = sc.parallelize(range(1, n + 1), partitions).map(f).reduce(add)<br>print(&quot;Pi is roughly %f&quot; % (4.0 * count / n))</pre><p>Your output should be:</p><pre>Pi is roughly 3.141397</pre><h3>Extinguish the Spark</h3><p>After you have completed your development, you can shutdown your Spark cluster by simply executing:</p><pre>sc.stop()</pre><p>That will instruct your SparkContext to tear down the worker Pods you created above via the kube-apiserver.</p><p>To verify:</p><pre>$ kubectl get pods -n spark<br>NAME                                      READY   STATUS        RESTARTS   AGE<br>my-notebook-deployment-7bf574447c-pdn2q   1/1     Running       0          20m<br>spark-1581043649282-exec-1                0/1     Terminating   0          16m<br>spark-1581043651262-exec-2                1/1     Terminating   0          16m<br>spark-1581043651392-exec-3                1/1     Terminating   0          16m<br>spark-1581043651510-exec-4                0/1     Terminating   0          16m<br>spark-1581043651623-exec-5                0/1     Terminating   0          16m<br>spark-1581043656753-exec-6                0/1     Terminating   0          16m<br>spark-1581043656875-exec-7                0/1     Terminating   0          16m</pre><p>And now you are left with just your deployment/driver Pod in the spark namespace.</p><h3>Conclusion</h3><p>I hope you are now more confident creating a Spark cluster on Kubernetes using PySpark and appreciate the architecture behind it.</p><p>I know I used to run in stand alone mode for most of my early stage Spark development work, but now with Kubernetes support, it’s cluster or bust!</p><p>Feel free to post any questions, corrections, or concerns below and Happy Spark’ing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68f3f988f642" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ignite-the-spark-68f3f988f642">Ignite the Spark!</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>