<?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 Yuwei Sung on Medium]]></title>
        <description><![CDATA[Stories by Yuwei Sung on Medium]]></description>
        <link>https://medium.com/@yuweisung?source=rss-8b33def5f214------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JtlepB1jbg5UmOBP</url>
            <title>Stories by Yuwei Sung on Medium</title>
            <link>https://medium.com/@yuweisung?source=rss-8b33def5f214------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:22:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yuweisung/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[Serving LLM locally using LM Studio]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://yuweisung.medium.com/serving-llm-locally-using-lm-studio-c83baa552768?source=rss-8b33def5f214------2"><img src="https://cdn-images-1.medium.com/max/1175/1*2ihAdX0INgCH7bK_-6Mauw.png" width="1175"></a></p><p class="medium-feed-snippet">Thanks to ChatGPT. We don&#x2019;t need to go through Google search results and &#x201C;determine&#x201D; which link gives the right answer. ChatGPT is a&#x2026;</p><p class="medium-feed-link"><a href="https://yuweisung.medium.com/serving-llm-locally-using-lm-studio-c83baa552768?source=rss-8b33def5f214------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://yuweisung.medium.com/serving-llm-locally-using-lm-studio-c83baa552768?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/c83baa552768</guid>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[lm-studio]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 01:00:10 GMT</pubDate>
            <atom:updated>2025-02-25T01:00:10.989Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Running SparkPi SparkApplication in k8s homelab with Harbor Registry]]></title>
            <link>https://yuweisung.medium.com/running-sparkpi-sparkapplication-in-k8s-homelab-with-harbor-registry-8b289b111c24?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b289b111c24</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[ceph]]></category>
            <category><![CDATA[kubeflow]]></category>
            <category><![CDATA[harbor]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 18:24:30 GMT</pubDate>
            <atom:updated>2024-12-10T19:22:22.837Z</atom:updated>
            <content:encoded><![CDATA[<p>Running Spark applications requires infrastructure support, and most articles and books recommend using cloud providers to simplify the infra processes—for example, Google Dataproc, Databricks Community version, Azure HDInsight, or AWS EMR. If you want to learn/practice Spark/Delta Lake, the free cluster from cloud providers is good enough. When you want to get serious about machine learning, data pipeline, or workflow, the cost of the cloud providers adds up. Many customers are starting to pull back the cloud footprint and move their workloads to private data centers. In this series, I want to show the building process of my data analytic learning journey in my home lab using k8s. <br>Recently, I started to learn Spark and Delta Lake. Spark is a distributed computing platform that consumes structured/unstructured/streaming data and produces new insights into different analytic endpoints. After getting an overall idea of what Spark could do using local machines, I wondered how to streamline the data processes and CICD pipeline like a “real” data engineer/scientist with my home lab. It turns out Spark does support Kubernetes. I should be able to run any Spark jobs in my home lab. Spark and Delta Lake support local file systems, Hadoop, and Object Store (AWS S3, Google CloudStorage, and Azure Blob Storage). I do have Ceph Object Store in my lab. I also found the Spark operator in the Kubeflow project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*2Id13i9qHPyihOx2IIlCwQ.png" /></figure><p>In this first article, I show a manifest of the Spark operator installation, the steps to push Spark application images to the harbor registry, and the manifest of the Spark application accessing the Ceph object storage.</p><p>The first thing is “installing the Spark Operator”. Refer to<a href="https://github.com/kubeflow/spark-operator"> Kubeflow GitHub</a> for the Spark operator installation. There is a Sparkpi example that you can directly apply to the operator too.</p><pre># Add the Helm repository<br>helm repo add spark-operator https://kubeflow.github.io/spark-operator<br>helm repo update<br><br># Install the operator into the spark-operator namespace and wait for deployments to be ready<br>helm install spark-operator spark-operator/spark-operator \<br>    --namespace spark-operator --create-namespace --wait<br>kubectl apply -f https://raw.githubusercontent.com/kubeflow/spark-operator/refs/heads/master/examples/spark-pi.yaml</pre><p>You should see the spark-pi-driver job in action in your default namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00GhOkP0huolqyA3BuycyQ.png" /></figure><p>You can check the log and find the output (Pi is roughly 3.1416340862832683).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4OkIs86QF5fluXCZwga5Q.png" /></figure><p>This shows that the Spark operator is monitoring the SparkApplication CR and deploying the Spark Pi job correctly. Let’s check the SparkApplication CR.</p><pre>apiVersion: sparkoperator.k8s.io/v1beta2<br>kind: SparkApplication<br>metadata:<br>  name: spark-pi<br>  namespace: default<br>spec:<br>  type: Scala<br>  mode: cluster<br>  image: spark:3.5.3<br>  imagePullPolicy: IfNotPresent<br>  mainClass: org.apache.spark.examples.SparkPi<br>  mainApplicationFile: local:///opt/spark/examples/jars/spark-examples.jar<br>  arguments:<br>  - &quot;5000&quot;<br>  sparkVersion: 3.5.3<br>  driver:<br>    labels:<br>      version: 3.5.3<br>    cores: 1<br>    memory: 512m<br>    serviceAccount: spark-operator-spark<br>  executor:<br>    labels:<br>      version: 3.5.3<br>    instances: 1<br>    cores: 1<br>    memory: 512m</pre><p>This Pi job does not read from any data source nor write the result in the console. One more concern is that you need to customize the image to serve your data process use cases. For example, you may need to install additional Python modules or Spark connectors to read/write data to external analytic endpoints. This means my data engineers will need to write the Spark application logic locally and push the container image to a private/public registry. Next step, I show how I pull and push images from dockerhub to the harbor registry in my home lab. Refer to my <a href="https://medium.com/@yuweisung/harbor-cert-manager-self-signed-ca-and-containerd-docker-troubleshooting-16b48b34503d">article</a> about harbor registry installation.</p><p>If you are using a Mac, be aware of the “platform” you pull/push. My homelab nodes are Linux and only capable of running amd64. If you accidentally push arm images, you will see an “error” running the job.</p><pre>#from my mac, docker login to my harbor registry<br>docker login https://harbor.home.lab<br>Authenticating with existing credentials...<br>Login Succeeded<br>#pull spark image from dockerhub with amd64 arch<br>docker pull --platform linux/amd64 spark:3.5.3<br>docker tag spark:3.5.3 harbor.home.lab/homelab/spark:3.5.3<br>docker push harbor.home.lab/homelab/spark:3.5.3<br>...</pre><p>Double-check that the image was pushed to my private registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EjEIpU-srUHwbORFrB7Lg.png" /></figure><p>Let’s redeploy the Spark Pi application using the new image. Note that I changed the imagePullPolicy to “always” in case the code is modified. The purpose is to make sure the Spark operator can work with my private harbor registry.</p><pre>apiVersion: sparkoperator.k8s.io/v1beta2<br>kind: SparkApplication<br>metadata:<br>  name: spark-pi<br>  namespace: default<br>spec:<br>  type: Scala<br>  mode: cluster<br>  image: harbor.home.lab/homelab/spark:3.5.3<br>  imagePullPolicy: Always<br>  mainClass: org.apache.spark.examples.SparkPi<br>  mainApplicationFile: local:///opt/spark/examples/jars/spark-examples.jar<br>  arguments:<br>  - &quot;5000&quot;<br>  sparkVersion: 3.5.3<br>  driver:<br>    labels:<br>      version: 3.5.3<br>    cores: 1<br>    memory: 512m<br>    serviceAccount: spark-operator-spark<br>  executor:<br>    labels:<br>      version: 3.5.3<br>    instances: 1<br>    cores: 1<br>    memory: 512m</pre><p>The job is completed without a problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDEZXAKruJgI9beuOZSrEQ.png" /></figure><p>Next, let’s set up the Ceph ObjectStore and verify the Spark Application can read/write to the object store bucket. Refer to the <a href="https://rook.io/docs/rook/latest/Getting-Started/quickstart/">Rook/Ceph document</a> for installation. Here is my CephObjectStore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*No-sibirMtMBqBHHdwt2lA.png" /></figure><p>This is the CR for my CepObjectStore, StorageClass, and ObjectBucketClaim for the Spark application.</p><pre>apiVersion: ceph.rook.io/v1<br>kind: CephObjectStore<br>metadata:<br>  name: homelab<br>  namespace: rook-ceph<br>spec:<br>  metadataPool:<br>    failureDomain: host<br>    replicated:<br>      size: 3<br>  dataPool:<br>    failureDomain: host<br>    # For production it is recommended to use more chunks, such as 4+2 or 8+4<br>    erasureCoded:<br>      dataChunks: 2<br>      codingChunks: 1<br>  preservePoolsOnDelete: false<br>  gateway:<br>    # annotations:<br>    #   metallb.universe.tf/loadBalancerIPs: 10.10.0.39<br>    # sslCertificateRef: ceph-homelab-tls<br>    # caBundleRef: homelab<br>    port: 80<br>    #securePort: 443<br>    instances: 1<br>---<br>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: rook-ceph-delete-bucket<br>provisioner: rook-ceph.ceph.rook.io/bucket # driver:namespace:cluster<br># set the reclaim policy to delete the bucket and all objects<br># when its OBC is deleted.<br>reclaimPolicy: Delete<br>parameters:<br>  objectStoreName: homelab<br>  objectStoreNamespace: rook-ceph # namespace:cluster<br>  # To accommodate brownfield cases reference the existing bucket name here instead<br>  # of in the ObjectBucketClaim (OBC). In this case the provisioner will grant<br>  # access to the bucket by creating a new user, attaching it to the bucket, and<br>  # providing the credentials via a Secret in the namespace of the requesting OBC.<br>  #bucketName:<br>---<br>apiVersion: objectbucket.io/v1alpha1<br>kind: ObjectBucketClaim<br>metadata:<br>  name: spark-object-store<br>spec:<br>  # To create a new bucket specify either `bucketName` or<br>  # `generateBucketName` here. Both cannot be used. To access<br>  # an existing bucket the bucket name needs to be defined in<br>  # the StorageClass referenced here, and both `bucketName` and<br>  # `generateBucketName` must be omitted in the OBC.<br>  #bucketName:<br>  generateBucketName: ceph-bkt<br>  storageClassName: rook-ceph-delete-bucket<br>  additionalConfig:<br>    # To set for quota for OBC<br>    #maxObjects: &quot;1000&quot;<br>    #maxSize: &quot;2G&quot;</pre><p>Once the object bucket is ready, we can write a container image to send data to the bucket. Here is the information on the object store needed by a Spark job (AWS 3S Host, name, port, access key ID, and secret access key). The SparkApplication CR should be able to mount the secret and configMap to access the object store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHmsAgrk3FIXMAujqMutlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifmKaQlZlNwNzCx1K7EjnQ.png" /></figure><p>Let’s test the bucket access with the rook/ceph toolbox operator. Deploy a toolbox operator <a href="https://github.com/rook/rook/blob/master/deploy/examples/toolbox-operator-image.yaml">deployment </a>and shell into the pod. Note that the “toolbox” deployment does not have s5cmd.</p><pre>export AWS_HOST=rook-ceph-rgw-homelab.rook-ceph.svc<br>export PORT=80<br>export BUCKET_NAME=ceph-bkt-7c5f4833-e3ff-4830-84fb-21a6470bc508<br>export AWS_ACCESS_KEY_ID=RGLCL15NVEOTKFXRRUI5<br>export AWS_SECRET_ACCESS_KEY=i9q5BxZJME984bH5wq8s8aZPv9uDHEnnel1Z1I4D<br>echo &quot;Hello Rook&quot; &gt; /tmp/rookObj<br># cp /tmp/rookObj to s3 bucket<br>s5cmd --endpoint-url http://$AWS_HOST:$PORT cp /tmp/rookObj s3://$BUCKET_NAME<br># you should get the following response<br>cp /tmp/rookObj s3://ceph-bkt-7c5f4833-e3ff-4830-84fb-21a6470bc508/rookObj<br># download the same file from s3 bucket<br>s5cmd --endpoint-url http://$AWS_HOST:$PORT cp s3://$BUCKET_NAME/rookObj /tmp/rookObj-download<br># you should get the following response<br>cp s3://ceph-bkt-7c5f4833-e3ff-4830-84fb-21a6470bc508/rookObj /tmp/rookObj-download<br># if you cat /tmp/rookObj-download<br>cat /tmp/rookObj-download<br>Hello Rook</pre><p>It’s time to write a pySpark container image. Ceph ObjectStore supports s3a protocol, but the default spark image does not have the jar included. I need to add two jars to the image. Also, due to the self-signed/private ca, I used in my home lab, I need to make a new image with my root.crt so pySpark and hadoop-aws can pick up the trust store in JVM. Here is my Dockerfile.</p><pre>FROM spark:3.5.3<br><br>WORKDIR /opt/spark<br>USER root<br><br>RUN apt upgrade -y<br>RUN wget https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-aws/3.3.4/hadoop-aws-3.3.4.jar -P $SPARK_HOME/jars<br>RUN wget https://repo1.maven.org/maven2/com/amazonaws/aws-java-sdk-bundle/1.12.262/aws-java-sdk-bundle-1.12.262.jar -P $SPARK_HOME/jars<br>COPY root.crt /opt/spark<br>RUN keytool -import -trustcacerts -file /opt/spark/root.crt -alias homelab  -keystore /opt/java/openjdk/lib/security/cacerts -noprompt -storepass changeit<br>RUN rm /opt/spark/root.crt<br><br>USER spark<br>ENTRYPOINT [ &quot;/opt/entrypoint.sh&quot; ]</pre><p>This is the command I build the new image.</p><pre>docker buildx build --platform linux/amd64 -t spark:3.5.3 .<br>docker tag spark:3.5.3 harbor.home.lab/homelab/spark:3.5.3<br>docker push harbor.home.lab/homelab/spark:3.5.3</pre><p>Next, I create a deployment to test this new image with pySpark. In this deployment, I mount the ceph-bucket secret and configMap (containing S3 endpoint and credential) as env. Note that I changed the command and args of the container, so I have a chance to shell into the container and run pySpark.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: sptest<br>  labels:<br>    app: spark<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: spark<br>  template:<br>    metadata:<br>      labels:<br>        app: spark<br>    spec:<br>      containers:<br>      - name: spark<br>        image: harbor.home.lab/homelab/spark:3.5.3<br>        imagePullPolicy: Always<br>        command: [&quot;/bin/bash&quot;]<br>        args: [&quot;-c&quot;, &quot;while true; do sleep 100; done&quot;]<br>        envFrom:<br>          - configMapRef:<br>              name: ceph-bucket<br>          - secretRef:<br>              name: ceph-bucket</pre><p>After the deployment is running, shell into the pod and run the following commands in pySpark.</p><pre>import os<br>access_key = os.getenv(&#39;AWS_ACCESS_KEY_ID&#39;)<br>secret_key = os.getenv(&#39;AWS_SECRET_ACCESS_KEY&#39;)<br>s3_host = os.getenv(&#39;BUCKET_HOST&#39;)<br>s3_port = os.getenv(&#39;BUCKET_PORT&#39;)<br>bucket = os.getenv(&#39;BUCKET_NAME&#39;)<br>s3_endpoint = f&quot;https://{s3_host}:{s3_port}&quot;<br>s3_url = f&quot;s3a://{bucket}/test&quot;<br><br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.impl&#39;, &#39;org.apache.hadoop.fs.s3a.S3AFileSystem&#39;)<br>sc._jsc.hadoopConfiguration().set(&#39;com.amazonaws.sdk.disableCertChecking&#39;, &#39;true&#39;)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.endpoint&#39;, s3_endpoint)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.access.key&#39;, access_key)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.secret.key&#39;, secret_key)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.connection.ssl.strictverify&#39;, &#39;false&#39;)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.path.style.access&#39;, &#39;true&#39;)<br><br>data = spark.range(0,100)<br>data.write.format(&#39;parquet&#39;).mode(&#39;overwrite&#39;).save(s3_url)</pre><p>If everything is fine, you should see the following.</p><pre>24/12/09 22:23:22 WARN MetricsConfig: Cannot locate configuration: tried hadoop-metrics2-s3a-file-system.properties,hadoop-metrics2.properties<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 95.00% for 8 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 84.44% for 9 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 76.00% for 10 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 69.09% for 11 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 63.33% for 12 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 58.46% for 13 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 54.29% for 14 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 50.67% for 15 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 47.50% for 16 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 44.71% for 17 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 42.22% for 18 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 40.00% for 19 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 38.00% for 20 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 36.19% for 21 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 34.55% for 22 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 33.04% for 23 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 31.67% for 24 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 33.04% for 23 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 34.55% for 22 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 36.19% for 21 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 38.00% for 20 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 40.00% for 19 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 42.22% for 18 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 44.71% for 17 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 47.50% for 16 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 50.67% for 15 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 54.29% for 14 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 58.46% for 13 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 63.33% for 12 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 69.09% for 11 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 76.00% for 10 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 84.44% for 9 writers<br>24/12/09 22:23:24 WARN MemoryManager: Total allocation exceeds 95.00% (1,020,054,720 bytes) of heap memory<br>Scaling row group sizes to 95.00% for 8 writers<br>&gt;&gt;&gt;</pre><p>The above output confirms that the “root.crt import” resolves the private ca.crt issue when using aws-hadoop lib to access Ceph Object store with TLS.<br>In the final step, I added the same Python script to the Dockerfile and built it again for SparkApplication CR. The Python script looks like this.</p><pre>import os<br>from pyspark.sql import SparkSession<br>spark = SparkSession.builder.getOrCreate()<br>sc = spark.sparkContext<br><br>access_key = os.getenv(&#39;AWS_ACCESS_KEY_ID&#39;)<br>secret_key = os.getenv(&#39;AWS_SECRET_ACCESS_KEY&#39;)<br>s3_host = os.getenv(&#39;BUCKET_HOST&#39;)<br>s3_port = os.getenv(&#39;BUCKET_PORT&#39;)<br>bucket = os.getenv(&#39;BUCKET_NAME&#39;)<br>s3_endpoint = f&quot;https://{s3_host}:{s3_port}&quot;<br>s3_url = f&quot;s3a://{bucket}/test&quot;<br><br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.impl&#39;, &#39;org.apache.hadoop.fs.s3a.S3AFileSystem&#39;)<br>sc._jsc.hadoopConfiguration().set(&#39;com.amazonaws.sdk.disableCertChecking&#39;, &#39;true&#39;)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.endpoint&#39;, s3_endpoint)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.access.key&#39;, access_key)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.secret.key&#39;, secret_key)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.connection.ssl.strictverify&#39;, &#39;false&#39;)<br>sc._jsc.hadoopConfiguration().set(&#39;fs.s3a.path.style.access&#39;, &#39;true&#39;)<br><br>data = spark.range(0,100)<br>data.write.format(&#39;parquet&#39;).mode(&#39;overwrite&#39;).save(s3_url)</pre><p>Add the Python file to the work-dir. The new Dockerfile looks like this.</p><pre>FROM spark:3.5.3<br><br>WORKDIR /opt/spark<br>USER root<br><br>RUN apt upgrade -y<br>RUN wget https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-aws/3.3.4/hadoop-aws-3.3.4.jar -P $SPARK_HOME/jars<br>RUN wget https://repo1.maven.org/maven2/com/amazonaws/aws-java-sdk-bundle/1.12.262/aws-java-sdk-bundle-1.12.262.jar -P $SPARK_HOME/jars<br>COPY root.crt /opt/spark<br>RUN keytool -import -trustcacerts -file /opt/spark/root.crt -alias homelab  -keystore /opt/java/openjdk/lib/security/cacerts -noprompt -storepass changeit<br>RUN rm /opt/spark/root.crt<br>COPY run.py /opt/spark/work-dir<br><br>USER spark<br>ENTRYPOINT [ &quot;/opt/entrypoint.sh&quot; ]</pre><p>After the new image is pushed to the harbor registry, we can apply the SparkApplication CR and check the output in the Ceph Object Store.</p><pre>apiVersion: sparkoperator.k8s.io/v1beta2<br>kind: SparkApplication<br>metadata:<br>  name: spark-ceph<br>  namespace: default<br>spec:<br>  type: Python<br>  pythonVersion: &quot;3&quot;<br>  mainApplicationFile: local:///opt/spark/work-dir/run.py<br>  mode: cluster<br>  image: harbor.home.lab/homelab/spark-py:3.5.3<br>  deps:<br>  sparkConf:<br>  hadoopConf:<br>  driver:<br>    cores: 1<br>    memory: &quot;512m&quot;<br>    serviceAccount: spark-operator-spark<br>    envFrom:<br>      - configMapRef:<br>          name: ceph-bucket<br>      - secretRef:<br>          name: ceph-bucket<br>    javaOptions:<br>    volumeMounts:<br>    - name: sparky-data<br>      mountPath: /spark-data<br>  executor:<br>    cores: 1<br>    instances: 2<br>    memory: &quot;512m&quot;<br>    envFrom:<br>      - configMapRef:<br>          name: ceph-bucket<br>      - secretRef:<br>          name: ceph-bucket</pre><p>There are many options to run a data pipeline in a Kubernetes cluster. In this article, I show the possibility of running a basic spark job using Ceph Object Store. More questions pop up in my brain. What else do I need to automate/version/monitor/collaborate the data pipeline? Argo? Delta Lake? GitHub/Gitea? Keycloak for rbac? security (cve)? Next article, I will try data pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b289b111c24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jupyter Notebook with Delta-spark in Multipass]]></title>
            <link>https://yuweisung.medium.com/jupyter-notebook-with-delta-spark-in-multipass-4af10ada35fe?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/4af10ada35fe</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[multipass]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 19:26:30 GMT</pubDate>
            <atom:updated>2024-12-02T02:07:19.666Z</atom:updated>
            <content:encoded><![CDATA[<p>Following my <a href="https://yuweisung.medium.com/setting-up-delta-spark-on-mac-using-multipass-ubuntu24-04-928f84d2b822">latest article</a>, I want to use Jupyter Notebook to record my learning of Delta. The setup is pretty straightforward. <br>First, shell into the multipass instance and install jupyter using pip.</p><pre>[~/git/delta]$ multipass shell delta<br># in ubuntu instance and pyspark venv<br>(pyspark) ubuntu@delta:~$ pip install jupyter<br>...<br>(pyspark) ubuntu@delta:~$</pre><p>Second, typical house cleaning of jupyter notebook, disabling fd output in notebook. In addition, I want to start jupyter notebook when shell to the instance, so the shell becomes jupyter log console. I added the jupytor start script to .bashrc.</p><pre>(pyspark) ubuntu@delta:~$ ipython profile create<br>...<br>(pyspark) ubuntu@delta:~$ echo &#39;c.IPKernelApp.capture_fd_output = False&#39; &gt;&gt; .ipython/profile_default/ipython_kernel_config.py<br>(pyspark) ubuntu@delta:~$ echo &#39;jupyter notebook --no-browser --ip 0.0.0.0 --port 8888 --notebook-dir=&quot;/data&quot;&#39; &gt;&gt; .bashrc<br>(pyspark) ubuntu@delta:~$</pre><p>Exit the instance and run the multipass shell command again.</p><pre>[~/git/delta]$ multipass shell delta<br>Welcome to Ubuntu 24.04.1 LTS (GNU/Linux 6.8.0-49-generic aarch64)<br><br> * Documentation:  https://help.ubuntu.com<br> * Management:     https://landscape.canonical.com<br> * Support:        https://ubuntu.com/pro<br><br> System information as of Sat Nov 30 13:12:59 CST 2024<br><br>  System load:             0.0<br>  Usage of /:              47.9% of 8.65GB<br>  Memory usage:            12%<br>  Swap usage:              0%<br>  Processes:               126<br>  Users logged in:         0<br>  IPv4 address for enp0s1: 192.168.205.7<br>  IPv6 address for enp0s1: fd21:4101:a4fb:ee9c:5054:ff:fe2f:8805<br><br><br>Expanded Security Maintenance for Applications is not enabled.<br><br>0 updates can be applied immediately.<br><br>Enable ESM Apps to receive additional future security updates.<br>See https://ubuntu.com/esm or run: sudo pro status<br><br><br>Last login: Sat Nov 30 12:42:04 2024 from 192.168.205.1<br>[I 2024-11-30 13:13:00.262 ServerApp] jupyter_lsp | extension was successfully linked.<br>[I 2024-11-30 13:13:00.264 ServerApp] jupyter_server_terminals | extension was successfully linked.<br>[I 2024-11-30 13:13:00.266 ServerApp] jupyterlab | extension was successfully linked.<br>[I 2024-11-30 13:13:00.267 ServerApp] notebook | extension was successfully linked.<br>[I 2024-11-30 13:13:00.356 ServerApp] notebook_shim | extension was successfully linked.<br>[I 2024-11-30 13:13:00.363 ServerApp] notebook_shim | extension was successfully loaded.<br>[I 2024-11-30 13:13:00.365 ServerApp] jupyter_lsp | extension was successfully loaded.<br>[I 2024-11-30 13:13:00.365 ServerApp] jupyter_server_terminals | extension was successfully loaded.<br>[I 2024-11-30 13:13:00.366 LabApp] JupyterLab extension loaded from /home/ubuntu/pyspark/lib/python3.12/site-packages/jupyterlab<br>[I 2024-11-30 13:13:00.366 LabApp] JupyterLab application directory is /home/ubuntu/pyspark/share/jupyter/lab<br>[I 2024-11-30 13:13:00.366 LabApp] Extension Manager is &#39;pypi&#39;.<br>[W 2024-11-30 13:13:00.366 LabApp] Failed to instantiate the extension manager pypi. Falling back to read-only manager.<br>    Traceback (most recent call last):<br>      File &quot;/home/ubuntu/pyspark/lib/python3.12/site-packages/jupyterlab/labapp.py&quot;, line 837, in initialize_handlers<br>        ext_manager = manager_factory(app_options, listings_config, self)<br>                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>      File &quot;/home/ubuntu/pyspark/lib/python3.12/site-packages/jupyterlab/extensions/__init__.py&quot;, line 46, in get_pypi_manager<br>        return PyPIExtensionManager(app_options, ext_options, parent)<br>               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>      File &quot;/home/ubuntu/pyspark/lib/python3.12/site-packages/jupyterlab/extensions/pypi.py&quot;, line 134, in __init__<br>        self._httpx_client = httpx.AsyncClient(proxies=proxies)<br>                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>    TypeError: AsyncClient.__init__() got an unexpected keyword argument &#39;proxies&#39;<br>[I 2024-11-30 13:13:00.368 ServerApp] jupyterlab | extension was successfully loaded.<br>[I 2024-11-30 13:13:00.369 ServerApp] notebook | extension was successfully loaded.<br>[I 2024-11-30 13:13:00.369 ServerApp] Serving notebooks from local directory: /data<br>[I 2024-11-30 13:13:00.369 ServerApp] Jupyter Server 2.14.2 is running at:<br>[I 2024-11-30 13:13:00.369 ServerApp] http://delta:8888/tree?token=879dd78cf1207e3ab64e7b4262c873d6247c0e236e33c430<br>[I 2024-11-30 13:13:00.369 ServerApp]     http://127.0.0.1:8888/tree?token=879dd78cf1207e3ab64e7b4262c873d6247c0e236e33c430<br>[I 2024-11-30 13:13:00.369 ServerApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).<br>[C 2024-11-30 13:13:00.371 ServerApp]</pre><p>The notebook should be ready for access from my local browser, but what ip? You can find the ip by running multipass info delta. Don’t forget to login the jupyter with the token showed in the log.</p><pre>[~/git/delta]$ multipass info delta<br>Name:           delta<br>State:          Running<br>Snapshots:      1<br>IPv4:           192.168.205.7<br>Release:        Ubuntu 24.04.1 LTS<br>Image hash:     6e1f90d3e81b (Ubuntu 24.04 LTS)<br>CPU(s):         4<br>Load:           0.02 0.01 0.00<br>Disk usage:     4.2GiB out of 9.6GiB<br>Memory usage:   340.8MiB out of 1.9GiB<br>Mounts:         /Users/ysung/git/delta =&gt; /data<br>                    UID map: 501:default<br>                    GID map: 20:default</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVmkc7yVbCcWcblVx9eHNA.png" /></figure><p>To verify this setup, I create a notebook folder and an ipython kernel note to test pyspark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kwb7iDvnJxDdJ363KuRpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbSdI0O0ZMTfW4kjfT56Ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZ2E0YlwqVgFO270JBuTkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bi2cru3IrigvqjOlTSh3fQ.png" /></figure><p>In sum, I added jupyter notebook to my delta tutorials. Keep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4af10ada35fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up delta-spark on Mac using Multipass]]></title>
            <link>https://yuweisung.medium.com/setting-up-delta-spark-on-mac-using-multipass-ubuntu24-04-928f84d2b822?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/928f84d2b822</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[multipass]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 06:23:03 GMT</pubDate>
            <atom:updated>2024-12-02T01:43:49.898Z</atom:updated>
            <content:encoded><![CDATA[<p>I spend a bit of time searching how to setup a local delta environment on mac and only find some container solutions (starting with spark images). Spark image is a fast pass to write your first spark job, but it hides the detail of environment setup. I need a bit of “ground up” approach. Recently I find M<a href="https://multipass.run/">ultipass</a> from Canonical is a fast way to bring up a Linux virtual machine in Apple Mac M2. This article is my beginning of delta lake journey.</p><p>First of all, it is pretty easy to setup Multipass in Mac, brew away…</p><pre># install multipass <br>brew install --cask multipass</pre><p>Once Multipass installed, you can use “launch” to get a virtual machine setup. In my case, I specify Ubuntu 24.04 image with 4 cpu, 2GB memory, 10GB disk, and local volume mount. You can find those launch options in Multipass command line help. After the instance is ready, you can shell into the instance like a docker container.</p><pre># launch 24.04<br>multipass launch 24.04 -c 4 -d 10G -m 2G --mount ~/git/delta:/data -n delta<br># shell into ubuntu<br>multipass shell delta<br>ubuntu@delta:~$</pre><p>After shelling into the instance, like other fresh installation, you need to do some package upgrades. Also, I follow Delta doc to 1) install jdk and python-venv, and 2) download/untar spark binary.</p><pre># upgrade packages<br>ubuntu@delta:~$sudo apt upgrade -y<br>...<br># install openjdk and python-venv<br>ubuntu@delta:~$sudo apt install -y default-jdk python3.12-venv<br>...<br># download spark binary<br>ubuntu@delta:~$wget https://dlcdn.apache.org/spark/spark-3.5.3/spark-3.5.3-bin-hadoop3.tgz<br>...<br># untar spark binary<br>ubuntu@delta:~$tar zxvf spark-3.5.3-bin-hadoop3.tgz<br>...<br># move binary to opt<br>ubuntu@delta:~$sudo mv spark-3.5.3-bin-hadoop3 /opt<br># delete the zip<br>ubuntu@delta:~$rm spark-3.5.3-bin-hadoop3.tgz<br># symlink spark<br>ubuntu@delta:~$sudo ln -s /opt/spark-3.5.3-bin-hadoop3 /opt/spark</pre><p>In most Linux distribution, python should be installed and many system services are using the system python libs. Direct install pyspark or delta-spark to system python is not recommended. So I use python venv in the following setup steps.</p><pre># create venv<br>ubuntu@delta:~$python3 -m venv pyspark<br># setup spark home, pyspark python path<br>ubuntu@delta:~$echo &#39;export SPARK_HOME=/opt/spark&#39; &gt;&gt; .bashrc<br>ubuntu@delta:~$echo &#39;export PATH=$PATH:$SPARK_HOME/bin:$SPARK_HOME/sbin&#39; &gt;&gt; .bashrc<br>ubuntu@delta:~$echo &#39;source ~/pyspark/bin/activate&#39; &gt;&gt; .bashrc<br>ubuntu@delta:~$echo &#39;export PYSPARK_DRIVER_PYTHON=python&#39; &gt;&gt; .bashrc<br>ubuntu@delta:~$echo &#39;export PYSPARK_PYTHON=~/pyspark/bin/python&#39; &gt;&gt; .bashrc<br>ubuntu@delta:~$source .bashrc<br># in pyspark venv<br>(pyspark) ubuntu@delta:~$</pre><p>Now it is safe to install delta-park using pip. Note that you should always checkout the delta vs spark compatibility.</p><pre>pyspark) ubuntu@delta:~$ pip install delta-spark==3.2.1<br>Collecting delta-spark==3.2.1<br>  Downloading delta_spark-3.2.1-py3-none-any.whl.metadata (1.9 kB)<br>Collecting pyspark&lt;3.6.0,&gt;=3.5.3 (from delta-spark==3.2.1)<br>  Downloading pyspark-3.5.3.tar.gz (317.3 MB)<br>     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 317.3/317.3 MB 11.4 MB/s eta 0:00:00<br>  Installing build dependencies ... done<br>  Getting requirements to build wheel ... done<br>  Preparing metadata (pyproject.toml) ... done<br>Collecting importlib-metadata&gt;=1.0.0 (from delta-spark==3.2.1)<br>  Downloading importlib_metadata-8.5.0-py3-none-any.whl.metadata (4.8 kB)<br>Collecting zipp&gt;=3.20 (from importlib-metadata&gt;=1.0.0-&gt;delta-spark==3.2.1)<br>  Downloading zipp-3.21.0-py3-none-any.whl.metadata (3.7 kB)<br>Collecting py4j==0.10.9.7 (from pyspark&lt;3.6.0,&gt;=3.5.3-&gt;delta-spark==3.2.1)<br>  Downloading py4j-0.10.9.7-py2.py3-none-any.whl.metadata (1.5 kB)<br>Downloading delta_spark-3.2.1-py3-none-any.whl (21 kB)<br>Downloading importlib_metadata-8.5.0-py3-none-any.whl (26 kB)<br>Downloading py4j-0.10.9.7-py2.py3-none-any.whl (200 kB)<br>   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 200.5/200.5 kB 16.2 MB/s eta 0:00:00<br>Downloading zipp-3.21.0-py3-none-any.whl (9.6 kB)<br>Building wheels for collected packages: pyspark<br>  Building wheel for pyspark (pyproject.toml) ... done<br>  Created wheel for pyspark: filename=pyspark-3.5.3-py2.py3-none-any.whl size=317840629 sha256=6ebe46664d2f3dad5c865a916608d71f7846fee6ab67b80278688aea8b173ade<br>  Stored in directory: /home/ubuntu/.cache/pip/wheels/07/a0/a3/d24c94bf043ab5c7e38c30491199a2a11fef8d2584e6df7fb7<br>Successfully built pyspark<br>Installing collected packages: py4j, zipp, pyspark, importlib-metadata, delta-spark<br>Successfully installed delta-spark-3.2.1 importlib-metadata-8.5.0 py4j-0.10.9.7 pyspark-3.5.3 zipp-3.21.0<br>(pyspark) ubuntu@delta:~$</pre><p>Following the delta doc, we can run a shell test, writing a series number to data volume we mount on the instance.</p><pre># run pyspark with delta<br>(pyspark) ubuntu@delta:~$pyspark --packages io.delta:delta-spark_2.12:3.2.0 \<br>  --conf &quot;spark.sql.extensions=io.delta.sql.DeltaSparkSessionExtension&quot; \<br>  --conf &quot;spark.sql.catalog.spark_catalog=org.apache.spark.sql.delta.catalog.DeltaCatalog&quot;<br>Python 3.12.3 (main, Nov  6 2024, 18:32:19) [GCC 13.2.0] on linux<br>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.<br>24/11/29 23:15:32 WARN Utils: Your hostname, delta resolves to a loopback address: 127.0.1.1; using 192.168.205.5 instead (on interface enp0s1)<br>24/11/29 23:15:32 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address<br>:: loading settings :: url = jar:file:/opt/spark-3.5.3-bin-hadoop3/jars/ivy-2.5.1.jar!/org/apache/ivy/core/settings/ivysettings.xml<br>Ivy Default Cache set to: /home/ubuntu/.ivy2/cache<br>The jars for the packages stored in: /home/ubuntu/.ivy2/jars<br>io.delta#delta-spark_2.12 added as a dependency<br>:: resolving dependencies :: org.apache.spark#spark-submit-parent-34282855-89d1-4291-88db-1a52c20bdfe7;1.0<br> confs: [default]<br> found io.delta#delta-spark_2.12;3.2.0 in central<br> found io.delta#delta-storage;3.2.0 in central<br> found org.antlr#antlr4-runtime;4.9.3 in central<br>downloading https://repo1.maven.org/maven2/io/delta/delta-spark_2.12/3.2.0/delta-spark_2.12-3.2.0.jar ...<br> [SUCCESSFUL ] io.delta#delta-spark_2.12;3.2.0!delta-spark_2.12.jar (308ms)<br>downloading https://repo1.maven.org/maven2/io/delta/delta-storage/3.2.0/delta-storage-3.2.0.jar ...<br> [SUCCESSFUL ] io.delta#delta-storage;3.2.0!delta-storage.jar (38ms)<br>downloading https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.9.3/antlr4-runtime-4.9.3.jar ...<br> [SUCCESSFUL ] org.antlr#antlr4-runtime;4.9.3!antlr4-runtime.jar (43ms)<br>:: resolution report :: resolve 2005ms :: artifacts dl 399ms<br> :: modules in use:<br> io.delta#delta-spark_2.12;3.2.0 from central in [default]<br> io.delta#delta-storage;3.2.0 from central in [default]<br> org.antlr#antlr4-runtime;4.9.3 from central in [default]<br> ---------------------------------------------------------------------<br> |                  |            modules            ||   artifacts   |<br> |       conf       | number| search|dwnlded|evicted|| number|dwnlded|<br> ---------------------------------------------------------------------<br> |      default     |   3   |   3   |   3   |   0   ||   3   |   3   |<br> ---------------------------------------------------------------------<br>:: retrieving :: org.apache.spark#spark-submit-parent-34282855-89d1-4291-88db-1a52c20bdfe7<br> confs: [default]<br> 3 artifacts copied, 0 already retrieved (6321kB/14ms)<br>24/11/29 23:15:35 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable<br>Setting default log level to &quot;WARN&quot;.<br>To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).<br>Welcome to<br>      ____              __<br>     / __/__  ___ _____/ /__<br>    _\ \/ _ \/ _ `/ __/  &#39;_/<br>   /__ / .__/\_,_/_/ /_/\_\   version 3.5.3<br>      /_/<br><br>Using Python version 3.12.3 (main, Nov  6 2024 18:32:19)<br>Spark context Web UI available at http://192.168.205.5:4040<br>Spark context available as &#39;sc&#39; (master = local[*], app id = local-1732943736264).<br>SparkSession available as &#39;spark&#39;.<br>&gt;&gt;&gt; data = spark.range(0,10)<br>&gt;&gt;&gt; data.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(&quot;/data/testShell&quot;)<br>&gt;&gt;&gt; exit()<br></pre><p>After exiting the pyspark prompt, we can find the data saved in the instance volume mount (/data). You can find _delta_log and 4 parquet files in the folder. The number of files may vary and depend on how many cpu you specify in the instance.</p><pre>#check the output<br>(pyspark) ubuntu@delta:~$ls /data/testShell/<br>_delta_log                                                           part-00002-5df0e7e7-40ef-4f2b-ad03-9ca7246cc5d3-c000.snappy.parquet<br>part-00000-d824cff5-439c-4915-bde0-ee23e41264e6-c000.snappy.parquet  part-00003-23f80fa3-c2f2-4d1d-a30f-9f7f88212a55-c000.snappy.parquet<br>part-00001-6fd3e51f-a381-45c0-a91c-fcd42cf26d95-c000.snappy.parquet</pre><p>After the task is done, exit the instance shell and stop the instance. Next time, you can just run multipass start delta and shell into the instance. Bonus, you can take snapshots in case something screw up.</p><pre>(pyspark) ubuntu@delta:~$ exit<br>logout<br># back to my iTerm2<br>[~/git/delta]$ ls testShell<br>_delta_log                                                          part-00002-5df0e7e7-40ef-4f2b-ad03-9ca7246cc5d3-c000.snappy.parquet<br>part-00000-d824cff5-439c-4915-bde0-ee23e41264e6-c000.snappy.parquet part-00003-23f80fa3-c2f2-4d1d-a30f-9f7f88212a55-c000.snappy.parquet<br>part-00001-6fd3e51f-a381-45c0-a91c-fcd42cf26d95-c000.snappy.parquet<br>[~/git/delta]$ multipass stop delta<br># take a snapshot<br>[~/git/delta]$ multipass snapshot delta -n spark-tutorial1<br>Snapshot taken: delta.spark-tutorial1<br>[~/git/delta]$</pre><p>This article summarizes my local delta-spark environment setup. Keep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=928f84d2b822" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gitea and Flux in my Private K8S Home Lab]]></title>
            <link>https://yuweisung.medium.com/gitea-and-flux-in-my-private-k8s-home-lab-281c552c6eb9?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/281c552c6eb9</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[flux]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Thu, 30 May 2024 00:01:27 GMT</pubDate>
            <atom:updated>2024-05-30T03:02:56.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BYKOaOm5fvxkrFDy" /><figcaption>Photo by <a href="https://unsplash.com/@amayli?utm_source=medium&amp;utm_medium=referral">Amélie Mourichon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Gitea is a Github-like opensource project. It is perfect for me in my homelab (private cloud) when I don’t want to push my code to github. In this tutorial, I demo how to install Gitea in my k8s env and use Flux cli to bootstrap gitea project.</p><p>First, I use <a href="https://docs.gitea.com/installation/install-on-kubernetes">helm to install </a>the gitea. The following is the values yaml file.</p><pre>podSecurityContext:<br>  fsGroup: 0<br>service:<br>  http:<br>    type: LoadBalancer<br>    loadBalancerIP: 10.10.0.37<br>    port: 443<br>    annotations:<br>      metallb.universe.tf/allow-shared-ip: &quot;gitea&quot;<br>  ssh:<br>    type: LoadBalancer<br>    loadBalancerIP: 10.10.0.37<br>    port: 22<br>    ClusterIP:<br>    annotations:<br>      metallb.universe.tf/allow-shared-ip: &quot;gitea&quot;<br>persistence:<br>  size: 100Gi<br>extraVolumes:<br>  - name: tls<br>    csi:<br>      driver: csi.cert-manager.io<br>      readOnly: true<br>      volumeAttributes:<br>        csi.cert-manager.io/issuer-name: ca-issuer<br>        csi.cert-manager.io/issuer-kind: ClusterIssuer<br>        csi.cert-manager.io/common-name: &quot;${SERVICE_ACCOUNT_NAME}.${POD_NAMESPACE}&quot;<br>        csi.cert-manager.io/dns-names: &quot;${POD_NAME}.${POD_NAMESPACE}.svc.cluster.local,gitea.home.lab&quot;<br>        csi.cert-manager.io/uri-sans: &quot;spiffe://cluster.local/ns/${POD_NAMESPACE}/pod/${POD_NAME}/${POD_UID}&quot;<br>        csi.cert-manager.io/ip-sans: 10.10.0.37<br>extraContainerVolumeMounts:<br>  - name: tls<br>    readOnly: true<br>    mountPath: /data/certs<br>gitea:<br>  podAnnotations:<br>  admin:<br>    username: &quot;ysung&quot;<br>    password: &quot;changeme&quot;<br>    email: &quot;ysung@mm2.home.lab&quot;<br>  config:<br>    database:<br>      DB_TYPE: postgres<br>    session:<br>      PROVIDER: db<br>    cache:<br>      ADAPTER: memory<br>    queue:<br>      TYPE: level<br>    indexer:<br>      ISSUE_INDEXER_TYPE: bleve<br>      REPO_INDEXER_ENABLED: true<br>    server:<br>      ROOT_URL: https://gitea.home.lab/<br>      PROTOCOL: https<br>      HTTP_PORT: 8443<br>      CERT_FILE: /data/certs/tls.crt<br>      KEY_FILE: /data/certs/tls.key<br>      SSH_DOMAIN: gitea.home.lab<br>      SSH_LISTEN_PORT: 2222<br>    webhook:<br>      SKIP_TLS_VERIFY: true<br>    actions:<br>      ENABLED: true<br>    <br>postgresql-ha:<br>  enabled: false<br>postgresql:<br>  enabled: true<br>redis-cluster:<br>  enabled: false</pre><p>From above yaml file, you can see that I use <a href="https://metallb.universe.tf/usage/#ip-address-sharing">metallb annotations</a> to share the LoadBalancer service IP between https and ssh services. Also, I have <a href="https://cert-manager.io/docs/usage/csi-driver/">cert-manager csi driver</a> to handle tls certificate and use “extraContainerVolumeMounts” to mount the tls cert. In gitea section, I specify where to find the tls cert and key.</p><p>Use the following command to install the gitea chart.</p><pre>helm install gitea -n gitea gitea/gitea --create-namespace</pre><p>Once the gitea deployed, both gitea-http and gitea-ssh share the same loadBalancer IP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zi6ShgvXp3rWYo4e1Czw_g.png" /></figure><p>I can login to “<a href="https://gitea.home.la./">https://gitea.home.la</a>b” with the credential in the yaml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cY3MYIrj7tDtEwl7rVvWA.png" /></figure><p>Next, I create a new Repository, datatesseract, under ysung user and test git pull from my laptop. The following code block shows the push.</p><pre>mkdir datatesseract<br>cd datatesseract<br>touch README.md<br>git init<br>Initialized empty Git repository in /Users/ysung/git/datatesseract/.git/<br>git checkout -b main<br>Switched to a new branch &#39;main&#39;<br>git add README.md<br>git commit -m &#39;first&#39;<br>[main (root-commit) f4e6482] first<br> 1 file changed, 0 insertions(+), 0 deletions(-)<br> create mode 100644 README.md<br>git remote add origin https://10.10.0.37/ysung/datatesseract.git<br>git push -u origin main<br>Enumerating objects: 3, done.<br>Counting objects: 100% (3/3), done.<br>Writing objects: 100% (3/3), 212 bytes | 212.00 KiB/s, done.<br>Total 3 (delta 0), reused 0 (delta 0), pack-reused 0<br>remote: . Processing 1 references<br>remote: Processed 1 references in total<br>To https://10.10.0.37/ysung/datatesseract.git<br> * [new branch]      main -&gt; main<br>branch &#39;main&#39; set up to track &#39;origin/main&#39;.</pre><p>Check the gitea web UI and the README.md is updated with the commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0UPodZ13w-Vz_kEyQKIuA.png" /></figure><p>Once we have a working gitea service, we can bootstrap Flux to monitoring this repo. Refer to <a href="https://fluxcd.io/flux/installation/bootstrap/gitea/">flux installation doc</a> for more detail. I found flux bootstrap is a good way to connect the gitea repository to flux in kubernetes. Here I use brew install fluxcd/tap/flux on my mac laptop. Run the precheck to verify the environment.</p><pre>brew install fluxcd/tap/flux<br>...<br>flux check --pre<br>► checking prerequisites<br>✔ Kubernetes 1.30.1 &gt;=1.28.0-0<br>✔ prerequisites checks passed</pre><p>Before we run the flux bootstrap, we need a personal access token from gitea. Go to gitea homepage -&gt; settings like the following snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*ajp4_PanFSljz-sHgn6nhQ.png" /></figure><p>on the left panel, find “applications” and give a token name, flux, specify the permissions, then click Generate Token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Ms6zM_HwI17SS5EMoGuHg.png" /></figure><p>Copy/paste the token because we need it during flux bootstrap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8Gbcw_DMWYg3Ln6EC4dFg.png" /></figure><p>Back to commandline and let’s bootstrap our first flux project.</p><pre>export GITEA_TOKE=xxxxxxxxxxxxxxxxxxx<br>flux bootstrap gitea --hostname=gitea.home.lab --owner=ysung --repository=datatesseract --private=false --path=clusters/homelab --insecure-skip-tls-verify<br>► connecting to gitea.home.lab<br>► cloning branch &quot;main&quot; from Git repository &quot;https://gitea.home.lab/ysung/datatesseract.git&quot;<br>✔ cloned repository<br>► generating component manifests<br>✔ generated component manifests<br>✔ committed component manifests to &quot;main&quot; (&quot;4d614f7c5949724411408107a622656061e4c871&quot;)<br>► pushing component manifests to &quot;https://gitea.home.lab/ysung/datatesseract.git&quot;<br>► installing components in &quot;flux-system&quot; namespace<br>✔ installed components<br>✔ reconciled components<br>► determining if source secret &quot;flux-system/flux-system&quot; exists<br>► generating source secret<br>✔ public key: ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBLN28DGO1EpniBUDZ+vFN8xjyZGwFUxDSIyyp2zJmcHOc9xMZxPeW85LMYaEVtPcONiqSussehLJ9oUO9hQMPaX3e0PVCOswmqYYqmF8xIzauu6fTUveU2cQWxgCYIGb2Q==<br>✔ configured deploy key &quot;flux-system-main-flux-system-./clusters/homelab&quot; for &quot;https://gitea.home.lab/ysung/datatesseract&quot;<br>► applying source secret &quot;flux-system/flux-system&quot;<br>✔ reconciled source secret<br>► generating sync manifests<br>✔ generated sync manifests<br>✔ committed sync manifests to &quot;main&quot; (&quot;3e00e6acc9506098136a29c97cf2e46d46e856e8&quot;)<br>► pushing sync manifests to &quot;https://gitea.home.lab/ysung/datatesseract.git&quot;<br>► applying sync manifests<br>✔ reconciled sync configuration<br>◎ waiting for GitRepository &quot;flux-system/flux-system&quot; to be reconciled<br>✔ GitRepository reconciled successfully<br>◎ waiting for Kustomization &quot;flux-system/flux-system&quot; to be reconciled<br>✔ Kustomization reconciled successfully<br>► confirming components are healthy<br>✔ helm-controller: deployment ready<br>✔ kustomize-controller: deployment ready<br>✔ notification-controller: deployment ready<br>✔ source-controller: deployment ready<br>✔ all components are healthy</pre><p>All components are healthy! Let’s check what has added in kubernetes and gitea repository. From the gitea homepage, you can see Flux manifests are added to the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P68ZSCHi24ceumwVudchag.png" /></figure><p>In the k8s cluster, you can see some operator-controllers added in flux-system namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3_dPfjlo_Ok2l-NRVsgCg.png" /></figure><p>TBC…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281c552c6eb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Pulsar KOP with Istio SNI routing]]></title>
            <link>https://yuweisung.medium.com/apache-pulsar-kop-with-istio-sni-routing-fdcf678efb25?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdcf678efb25</guid>
            <category><![CDATA[pulsar]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kops]]></category>
            <category><![CDATA[sn-platform]]></category>
            <category><![CDATA[istio]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Mon, 29 May 2023 03:18:26 GMT</pubDate>
            <atom:updated>2023-05-29T03:19:04.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vpTWyLIspWxDq71w" /><figcaption>Photo by <a href="https://unsplash.com/de/@helloimnik?utm_source=medium&amp;utm_medium=referral">Nik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, I demo how to setup Apache Pulsar KOP in K8S with Istio SNI routing using sn-platform helm chart.<br>The followings are executed in my home lab k8s setup by kubeadm. I use calico cni, rook-ceph csi, and metallb as layer2 load balancer. Also I setup ca cluster issuer (private signer) with cert-manager.</p><p>First, setup minimal istio with istioctl. You can follow the istio doc to install minimal (istio-operator only). We need to customize the ingress gateway ports to export some pulsar protocol ports.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5b7433b180ddb81e4b10e47372e9ea2/href">https://medium.com/media/a5b7433b180ddb81e4b10e47372e9ea2/href</a></iframe><p>The customized ingress gateway looks like this. Once you have istio installed in k8s cluster, you can use “<strong>istioctl install -f ingress-gateway.yaml -y</strong>” to deploy the ingress gateway.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a5e98fa3c1f1a23740ade9dccb522f5/href">https://medium.com/media/8a5e98fa3c1f1a23740ade9dccb522f5/href</a></iframe><p>Check the status of ingress-gateway svc using kubectl.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/766c7c01e5cced7ab52040da1d8447ad/href">https://medium.com/media/766c7c01e5cced7ab52040da1d8447ad/href</a></iframe><p>I also add a TLS certificate to the gateway in istio-system namespace.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2de27d0ebc670f0bd08ed6dac00feaab/href">https://medium.com/media/2de27d0ebc670f0bd08ed6dac00feaab/href</a></iframe><p>Now we are ready to deploy pulsar-operators and sn-platform with kop and istio sni routing. Refer to my previous pulsar blogs for details. In this blog, I use OLM to deploy pulsar operators.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4991b6b3d503afffd16fe431079a225/href">https://medium.com/media/e4991b6b3d503afffd16fe431079a225/href</a></iframe><p>Once those four operators are running, we can use sn-platform helm chart to set up kop and istio in one shot. Use the following sn-platform helm chart overrides to deploy the pulsar cluster. Some changes I made in this overrides, pulsar version to 2.11.1.1 and jvm heap size using ram percentage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8834e138906fde440e629ae4ea98dd14/href">https://medium.com/media/8834e138906fde440e629ae4ea98dd14/href</a></iframe><p>Review the overrides and deploy it using the helm install command line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a6872d8e1c1f893de3d7eea7fc5fb94/href">https://medium.com/media/4a6872d8e1c1f893de3d7eea7fc5fb94/href</a></iframe><p>After a while, you can check the status of “gateway”, “virtual service”, and “listener”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae4cf8d709445fd16f189d2c5ca8b291/href">https://medium.com/media/ae4cf8d709445fd16f189d2c5ca8b291/href</a></iframe><p>If you scale out broker (changing the broker replicaCount), you will see that the SNI routing is auto configured. Very nice.<br>Now let’s test KOP through the gateway. First, you need to setup kafak truststore because I use private ca in this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eeb57a0aa91faf00160bce7f7a819a8/href">https://medium.com/media/1eeb57a0aa91faf00160bce7f7a819a8/href</a></iframe><p>Once you have the client.properties, you can use kafka-console-producer.sh to send message to pulsar broker.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cf50efcbf62e7451fc48cdbb0c9091f/href">https://medium.com/media/2cf50efcbf62e7451fc48cdbb0c9091f/href</a></iframe><p>Then you can use either kafka-console-consumer.sh or pulsar-console-consumer.sh to receive the message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d603cd10d1a75cca2d15d07fc233c634/href">https://medium.com/media/d603cd10d1a75cca2d15d07fc233c634/href</a></iframe><p>Next blog, I will show OIDC/OAuth2 integration with sn-platform and kop.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdcf678efb25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harbor Registry with Keycloak OIDC]]></title>
            <link>https://yuweisung.medium.com/harbor-registry-with-keycloak-oidc-2c344f2d7a8c?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c344f2d7a8c</guid>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[harbor]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[sso]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Sat, 27 May 2023 20:39:29 GMT</pubDate>
            <atom:updated>2023-05-27T22:20:44.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jNZ1iMNBDqie8ZRx" /><figcaption>Photo by <a href="https://unsplash.com/de/@helloimnik?utm_source=medium&amp;utm_medium=referral">Nik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, I demo how to install and setup key cloak, then use Harbor Registry with OIDC authentication.</p><p>Keycloak is a single sign on solution that supports OAuth2, OpenID Connect (OIDC), and SAML. It is one of key components in cloud native platform. Before installing Keycloak in k8s, you need to setup a database and TLS certificate. Here is my ansible-playbook and manifest. Use ‘ansible-playbook’ to deploy it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc49f641c8b4a8ff685549aef545c5ab/href">https://medium.com/media/bc49f641c8b4a8ff685549aef545c5ab/href</a></iframe><p>From the above, you can see that I update my playbook with ansible k8s and helm modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f1ba740552b9accc1d23a6d01843c90/href">https://medium.com/media/8f1ba740552b9accc1d23a6d01843c90/href</a></iframe><p>In above manifest, I add a “pre-defined” realm json file as ConfigMap and use the postgresql db as the backend database. I use MetalLB as a layer2 load balancer and expose one of my home lab LAN IP and DNS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*iBoycndoGuCQ2yzQmo7C2g.png" /></figure><p>Click on “Administration Console” and you should be redirected to admin console. As the manifest showed, the login is admin/admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jj1FLiQoYb6bBwgCkwSEkw.png" /></figure><p>Switch to the “pre-created” realm, sn-lab, so we can start to setup client, user and roles. You can also create new Realm from the realm drop down box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPijzlR9sx_SzHDAKDUruQ.png" /></figure><p>In the bottom-left, under Configure, Click “realm settings” and you should see the realm OIDC Endpoints. The OpenID endpoint will bring you to the “well-known openid configuration”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LYukbGbSXhM15YQV0QTXA.png" /></figure><p>The endpoint contains all information you need to setup client application. In keycloak, the target application (harbor in this example) is called a “client”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngxBqYsHx10h6w0M5xRLFA.png" /></figure><p>Before continuing the client application setting, I deploy the harbor registry. Here is the ansible playbook and manifests. Use “ansible-playbook” to deploy the manifest.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8f24d2e8b4694a9ade5991baaf7bd8/href">https://medium.com/media/be8f24d2e8b4694a9ade5991baaf7bd8/href</a></iframe><p>The harbor service is also exposed as a load balancer in my home lab. The TLS certificate looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c55b11f7c035a363d30d2f69e7a724ac/href">https://medium.com/media/c55b11f7c035a363d30d2f69e7a724ac/href</a></iframe><p>After the deployment, you can access the harbor portal with the default username and password (admin/Harbor12345). You can change it in the helm chart values.yaml.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSnR1OdHMRuI7QSoV7i7fQ.png" /></figure><p>Once you have the access, note down the harbor URL (my example: <a href="https://harbor.home.lab/">https://harbor.home.lab</a>). We can go back to Keycloak and setup the client application (harbor). <br>In sn-lab realm, click “Clients” on the left panel and click “Create client”. Use the default “Client type”, OpenID Connect. Set the Client ID to “harbor”, give a Name “my homelab harbor”, then click Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izsc2f2ywiigrmurB_az1w.png" /></figure><p>In Capability config, turn ON “Client authentication”, check “Service accounts roles”, then click “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWe7rA_Pb_KHcv9YU3me2w.png" /></figure><p>In Login settings, give the harbor service URL(https://harbor.home.lab) in Root URL and Home URL, give the same service URLwith a wide card in Valid redirect URIs, then click “Save”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pXIoHY9hGxlN-EU4lzSoQ.png" /></figure><p>Once the client saved, you can see the harbor client details. Go to “Credentials” tab, make sure the “Client Authenticator” set to “Client Id and Secret”, then “copy” the “Client secret” to your notebook. We will need the secret in harbor authentication configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQMBdXcJQp6J_ojEOX_FKA.png" /></figure><p>On the left panel, click on “Users” and pick “Add user” to add our first single sign on user. The Required user actions are optional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCo_HSHHqw8P5qFlToJh0w.png" /></figure><p>After the test1 user is created, go to “Credentials” tab in the test1 user page and click “Set password”. You will need to type the password twice and keep “Temporary” ON. <br>Now we have the client application and a single sign on user created. Go back to harbor web UI to setup the authentication.<br>Login harbor as admin user and go to “Administration”, “Configuration”, click “Authentication”, then fill in the information as showing below. Make sure that 1) OIDC endpoint (https://kc.home.lab:8443/realms/sn-lab), 2) OIDC Client ID (harbor) and OIDC Client Secret are correct. In OIDC Scope, put “openid,profile,roles”. <br>If everything is good, click “TEST OIDC SERVER” and you should get a green bar showing it is success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkMZHMVHcH39Ni5hjJKivQ.png" /></figure><p>Now, log out the admin from the top-right and this should bring you back to the harbor login. You should see the new login option (LOGIN VIA OIDC PROVIDER).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwV3Ok_wIk4SI24WC2fvDw.png" /></figure><p>Now click on “LOGIN VIA OIDC PROVIDER” and you should see the login page. Type the single sign on username and password you just set in Keycloak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyHgupYnG-s4_ovaxRDejw.png" /></figure><p>Since I added a “Update Password” action when creating the user in Keycloak, the login page will ask you to update the password. After update the password and login with new password, you are in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUNd__WLqecxRluOxhCRTg.png" /></figure><p>This is part 1. Next part, let’s go back to Keycloak to setup different roles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c344f2d7a8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StreamNative Pulsar Operator Tutorial Part 3]]></title>
            <link>https://yuweisung.medium.com/streamnative-pulsar-operator-tutorial-part-3-2bb2cf67d0a0?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bb2cf67d0a0</guid>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[pulsar]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[streamnative]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Mon, 23 May 2022 18:37:41 GMT</pubDate>
            <atom:updated>2022-05-23T19:26:28.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SquKiMdx40ZtCtX6" /><figcaption>Photo by <a href="https://unsplash.com/@calebeangel?utm_source=medium&amp;utm_medium=referral">Caleb Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this part, I demo how to use ArgoCD to control Pulsar Custom Resource (CR) by monitoring the GitHub branch/tag.</p><p>In part 1, I created 4 pulsar CRs with pulsar version 2.9. I create a GitHub repository, pulsar-ops, to keep track of the CRs. ArgoCD will trace the changes in a folder of a branch, so I put all the CRs under the default folder.</p><pre><strong>➜  deployment git:(main) tree</strong><br>.<br>├── README.md<br>└── default<br>    ├── bk-cluster.yaml<br>    ├── br-cluster.yaml<br>    ├── px-cluster.yaml<br>    └── zk-cluster.yaml</pre><pre>1 directory, 5 files </pre><p>Once all the changes are committed, I add the remote to my GitHub target repo, tag the pulsar version, then push the CRs upstream.</p><pre><strong>➜  deployment git:(main) git remote add origin git@github.com:yuweisung/pulsar-ops.git</strong><br><strong>➜  deployment git:(main) git tag -a v2.9 -m &quot;pulsar-2.9&quot;</strong><br><strong>➜  deployment git:(main) git push --set-upstream origin v2.9</strong></pre><p>Now I can go to ArgoCD WebUI to create a pulsar cluster app. Login to ArgoCD, and create a new app with the following info, then click CREATE.</p><ul><li>Application Name: sn-platform</li><li>Project: default</li><li>SYNC POLICY: Automatic</li><li>Repository URL: <a href="https://github.com/yuweisung/pulsar-ops.git">https://github.com/yuweisung/pulsar-ops.git</a></li><li>Revision: v2.9 Tags</li><li>Path: default</li><li>Destination: <a href="https://kubernetes.default.svc/">https://kubernetes.default.svc</a></li><li>Namespace: sn-platform</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dF0PpGJYhtAkRNvxacS5Bw.png" /></figure><p>After the app is created, ArgoCD will scan the specific tag and syn the CRs to deploy the pulsar cluster as we did in part 1 using “kubectl apply -f”. The app detail shows the progress of the deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoMpGDEGpwoeOW-W8nFl-w.png" /></figure><p>A few minutes later, ArgoCD shows status synced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zyg4uPtZoXefJ4YbwSE9GA.png" /></figure><p>Next, I use git push and pull requests to control the CR details, e.g., adding JVM options, changing replicas of CR, and letting ArgoCD detect the changes and auto-apply the operation changes for me.</p><p>Open vs code and change the image version from 2.9.2.15 to 2.9.2.17 and commit the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_UjtZwKMH1XKmnf_P5SeA.png" /></figure><p>After committing the changes, I retag the commit to v2.9 and push with the force option.</p><pre><strong>➜  deployment git:(main) git tag -a -f v2.9 1ee752a</strong></pre><pre>Updated tag &#39;v2.9&#39; (was e40f3b6)<br><strong>➜  deployment git:(main) git push origin v2.9 --force</strong><br>Enumerating objects: 1, done.<br>Counting objects: 100% (1/1), done.<br>Writing objects: 100% (1/1), 165 bytes | 165.00 KiB/s, done.<br>Total 1 (delta 0), reused 0 (delta 0), pack-reused 0<br>To github.com:yuweisung/pulsar-ops.git<br> + e40f3b6...fc5fb8d v2.9 -&gt; v2.9 (forced update)</pre><p>ArgoCD detects the commit changes and syncs the status automatically. From the WebUI, you can see that some components are in “spinning” status as it follows the statefulset upgrade strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WxZ4tJeeRwKYOTwAc2sOQ.png" /></figure><p>Click on the zookeeper pod and you can see the image version updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blcgyPaZ6q2WtqsoA3yNXA.png" /></figure><p>Next, I want to use the same GitOps process to scale up/down brokers. Go back to the vs-code and modify the “br-cluster.yaml” file.</p><pre>apiVersion: pulsar.streamnative.io/v1alpha1<br>kind: PulsarBroker<br>metadata:<br>  name: my<br>  namespace: sn-platform<br>spec:<br>  image: streamnative/pulsar:2.9.2.17<br>  pod:<br>    resources:<br>      requests:<br>        cpu: 200m<br>        memory: 256Mi<br>    terminationGracePeriodSeconds: 30<br>  config:<br>    custom:<br>      webSocketServiceEnabled: &quot;true&quot;<br>  <strong>replicas: 3</strong><br>  zkServers: my-zk-headless:2181</pre><p>Then run the git commands to force retagging the new commit to v2.9 and to force pushing to the remote origin branch.</p><pre><strong>➜  deployment git:(main) git add default/br-cluster.yaml<br>➜  deployment git:(main) git commit -m &#39;scale up broker to 3&#39;</strong><br>[main 32e0468] scale up broker to 3<br> 1 file changed, 1 insertion(+), 1 deletion(-)<br><strong>➜  deployment git:(main) git tag -a -f v2.9 32e0468<br>➜  deployment git:(main) git push origin v2.9 --force</strong><br>Counting objects: 100% (8/8), done.<br>Delta compression using up to 10 threads<br>Compressing objects: 100% (5/5), done.<br>Writing objects: 100% (5/5), 516 bytes | 516.00 KiB/s, done.<br>Total 5 (delta 2), reused 0 (delta 0), pack-reused 0<br>remote: Resolving deltas: 100% (2/2), completed with 2 local objects.<br>To github.com:yuweisung/pulsar-ops.git<br> + fc5fb8d...13bf247 v2.9 -&gt; v2.9 (forced update)</pre><p>Back to the ArgoCD WebUI and the new broker (my-broker-2) is spinning up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6Vvtq8VN03TMMsc7x96fA.png" /></figure><p>With ArgoCD and GitHub, you can control pulsar CR changes. Next part, I will discuss how to add client-side (pulsar consume/producer) to the picture.<br>Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bb2cf67d0a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StreamNative Pulsar Operator Tutorial Part 2]]></title>
            <link>https://yuweisung.medium.com/streamnative-pulsar-operator-tutorial-part-2-8dd030ac1b7c?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd030ac1b7c</guid>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[apache-pulsar]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Mon, 16 May 2022 04:11:05 GMT</pubDate>
            <atom:updated>2022-05-18T12:44:54.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ia9_cS61V9ZLWCJ0" /><figcaption>Photo by <a href="https://unsplash.com/@will0629?utm_source=medium&amp;utm_medium=referral">Will Porada</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this part, I show a step-by-step how to create a python producer container using vs-code. I use venv to control the python version in a project. The following code snippet shows how I create python env and python libs before I open the folder using “code .”</p><pre><strong>mkdir cloudnative-pulsar<br>cd cloudnative-pulsar<br>python3 -m venv .py39<br>source .py39/bin/activate<br>python -m pip install --upgrade pip<br>pip install pulsar-client==2.9.2<br>git init<br>code . </strong></pre><p>My initial vs-code interface looks like this. I also toggle up a terminal window so I can run kubectl or docker build in the same window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*DJxOzPnDBB-QM33e9S9sLw.png" /></figure><p>In tutorial part 1, I exposed the proxy service as a load balancer (external IP). This way, I can connect to the broker in k8s directly from my home network. Next step, let’s jump into python producer and consumer. Use “command+shift P” to call up the vs-code command palette and type “new” and select “File: New Folder”, then add a folder called ‘producer’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*xFjR7VdT4LyGEYCr73EbcA.png" /></figure><p>Also, you can use the icon in the project explorer to create a new python file, ‘test_producer.py’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38OX8bvHyMl2A3sbiSnhmw.png" /></figure><p>Before you create a client (either producer or consumer), you need a topic created first. I used the “kubectl exec” to run the pulsar-admin command in the broker container and create a top in the vs-code terminal window.</p><pre><strong>kubectl exec -n sn-platform my-broker-0 -- bin/pulsar-admin topics create persistent://public/default/my-topic1</strong></pre><p>You should be able to see the topic created using the following command</p><pre><strong>kubectl exec -n sn-platform my-broker-0 -- bin/pulsar-admin topics list public/default</strong><br>&quot;persistent://public/default/my-topic1&quot;</pre><p>Now we are ready to type some python codes. Copy the following snippet to test_producer.py and save the file (cmd+s).</p><pre>import pulsar</pre><pre>client = pulsar.Client(&#39;pulsar://10.0.0.36:6650&#39;)</pre><pre>producer = client.create_producer(<br>    &#39;persistent://public/default/my-topic1&#39;,<br>    block_if_queue_full=True,<br>    batching_enabled=True,<br>    batching_max_publish_delay_ms=10)</pre><pre>def producer_callback(res, msg_id):<br>    print(f&quot;message published {msg_id}&quot;)</pre><pre>i = 0<br>while i &lt;1000:<br>    producer.send_async(<br>        f&quot;Hello-{i}&quot;.encode(&#39;utf-8&#39;),<br>        producer_callback)<br>    i+=1<br></pre><p>In the terminal, you can run the producer code like this.</p><pre><strong>source .py39/bin/activate</strong><br><strong>python producer/test_producer.py</strong><br>2022-05-15 21:49:46.917 INFO  [0x104948580] ClientConnection:182 | [&lt;none&gt; -&gt; pulsar://10.0.0.36:6650] Create ClientConnection, timeout=10000<br>2022-05-15 21:49:46.918 INFO  [0x104948580] ConnectionPool:96 | Created connection for pulsar://10.0.0.36:6650<br>2022-05-15 21:49:46.942 INFO  [0x16b81b000] ClientConnection:368 | [10.0.0.7:59912 -&gt; 10.0.0.36:6650] Connected to broker<br>2022-05-15 21:49:46.979 INFO  [0x16b81b000] HandlerBase:64 | [persistent://public/default/my-topic1, ] Getting connection from pool<br>2022-05-15 21:49:46.986 INFO  [0x16b81b000] ClientConnection:182 | [&lt;none&gt; -&gt; pulsar://10.0.0.36:6650] Create ClientConnection, timeout=10000<br>2022-05-15 21:49:46.986 INFO  [0x16b81b000] ConnectionPool:96 | Created connection for pulsar://my-broker-0.my-broker-headless.sn-platform.svc.cluster.local:6650<br>2022-05-15 21:49:46.993 INFO  [0x16b81b000] ClientConnection:370 | [10.0.0.7:59913 -&gt; 10.0.0.36:6650] Connected to broker through proxy. Logical broker: pulsar://my-broker-0.my-broker-headless.sn-platform.svc.cluster.local:6650<br>2022-05-15 21:49:47.040 INFO  [0x16b81b000] ProducerImpl:188 | [persistent://public/default/my-topic1, ] Created producer on broker [10.0.0.7:59913 -&gt; 10.0.0.36:6650]</pre><p>It looks good? The code returned without an error. How do we know it published 1000 messages to the topic? Let’s use the pulsar-admin to check the topic stats.</p><pre><strong>kubectl exec -n sn-platform my-broker-0 -- bin/pulsar-admin topics stats public/default/my-topic1</strong><br>Defaulted container &quot;pulsar-broker&quot; out of: pulsar-broker, init-sysctl (init)<br>{<br>  &quot;msgRateIn&quot; : 0.0,<br>  &quot;msgThroughputIn&quot; : 0.0,<br>  &quot;msgRateOut&quot; : 0.0,<br>  &quot;msgThroughputOut&quot; : 0.0,<br>  &quot;bytesInCounter&quot; : 14921,<br>  <strong>&quot;msgInCounter&quot; : 1000</strong>,<br>  &quot;bytesOutCounter&quot; : 0,<br>  &quot;msgOutCounter&quot; : 0,<br>  &quot;averageMsgSize&quot; : 0.0,<br>  &quot;msgChunkPublished&quot; : false,<br>  &quot;storageSize&quot; : 14921,<br>  &quot;backlogSize&quot; : 0,<br>  &quot;offloadedStorageSize&quot; : 0,<br>  &quot;lastOffloadLedgerId&quot; : 0,<br>  &quot;lastOffloadSuccessTimeStamp&quot; : 0,<br>  &quot;lastOffloadFailureTimeStamp&quot; : 0,<br>  &quot;publishers&quot; : [ ],<br>  &quot;waitingPublishers&quot; : 0,<br>  &quot;subscriptions&quot; : { },<br>  &quot;replication&quot; : { },<br>  &quot;deduplicationStatus&quot; : &quot;Disabled&quot;,<br>  &quot;nonContiguousDeletedMessagesRanges&quot; : 0,<br>  &quot;nonContiguousDeletedMessagesRangesSerializedSize&quot; : 0,<br>  &quot;compaction&quot; : {<br>    &quot;lastCompactionRemovedEventCount&quot; : 0,<br>    &quot;lastCompactionSucceedTimestamp&quot; : 0,<br>    &quot;lastCompactionFailedTimestamp&quot; : 0,<br>    &quot;lastCompactionDurationTimeInMills&quot; : 0<br>  }<br>}</pre><p>From this output, you can see that there are 1000 msgIn.</p><p>Next step, let’s build the image and make this producer a k8s deployment. Use the command palette to create a Dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*QS6y1_bUHFe6tREq9tNI_A.png" /></figure><p>You can find the Dockerfile and requirements.txt created in your project folder. I move the files to the producer folder and modified the content to fit the folder because I want to create two images, one for the producer and the other for the consumer.</p><p>Don’t forget to put the python dependency (pulsar-client==2.9.2) in the requirements.txt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7KHYOjJyyzxt69UP4C8Yg.png" /></figure><p>We are ready to build the docker image. Run the following command to build the image. Note that if you are using Mac M1, you need to specify the image platform to fit your k8s worker OS (mine is Ubuntu).</p><pre><strong>docker buildx build --platform linux/amd64 . -t yuwsung1/pulsar-python-producer:v0.1</strong><br><strong>docker push yuwsung1/pulsar-python-producer:v0.1</strong></pre><p>Once the image is pushed to the dockerhub, you can use kubectl to run the image as a container and check the topic stats for new messages.</p><pre><strong>kubectl run prod-test --image=yuwsung1/pulsar-python-producer:v0.1<br>kubectl exec -n sn-platform my-broker-0 -- bin/pulsar-admin topics stats public/default/my-topic1</strong><br>Defaulted container &quot;pulsar-broker&quot; out of: pulsar-broker, init-sysctl (init)<br>{<br>  &quot;msgRateIn&quot; : 0.0,<br>  &quot;msgThroughputIn&quot; : 0.0,<br>  &quot;msgRateOut&quot; : 0.0,<br>  &quot;msgThroughputOut&quot; : 0.0,<br>  <strong>&quot;bytesInCounter&quot; : 29482</strong>,<br>  <strong>&quot;msgInCounter&quot; : 2000</strong>,<br>  &quot;bytesOutCounter&quot; : 0,<br>  &quot;msgOutCounter&quot; : 0,<br>  &quot;averageMsgSize&quot; : 0.0,<br>  &quot;msgChunkPublished&quot; : false,<br>  &quot;storageSize&quot; : 14921,<br>  &quot;backlogSize&quot; : 0,<br>  &quot;offloadedStorageSize&quot; : 0,<br>  &quot;lastOffloadLedgerId&quot; : 0,<br>  &quot;lastOffloadSuccessTimeStamp&quot; : 0,<br>  &quot;lastOffloadFailureTimeStamp&quot; : 0,<br>  &quot;publishers&quot; : [ ],<br>  &quot;waitingPublishers&quot; : 0,<br>  &quot;subscriptions&quot; : { },<br>  &quot;replication&quot; : { },<br>  &quot;deduplicationStatus&quot; : &quot;Disabled&quot;,<br>  &quot;nonContiguousDeletedMessagesRanges&quot; : 0,<br>  &quot;nonContiguousDeletedMessagesRangesSerializedSize&quot; : 0,<br>  &quot;compaction&quot; : {<br>    &quot;lastCompactionRemovedEventCount&quot; : 0,<br>    &quot;lastCompactionSucceedTimestamp&quot; : 0,<br>    &quot;lastCompactionFailedTimestamp&quot; : 0,<br>    &quot;lastCompactionDurationTimeInMills&quot; : 0<br>  }<br>}</pre><p>However, this image is pretty much useless. The URL, topic name, and other producer properties are hard-coded in the python code. Next step, we set those properties to k8s configmap, then use deployment to mount those configmap as OS env variables. Then in the python code, we can import the os module and read the env variables to replace those properties. Now the producer codes like this:</p><pre>import pulsar<br><strong>import os</strong></pre><pre><strong>pulsar_url = os.environ.get(&#39;PULSAR_URL&#39;)</strong><br><strong>topic = os.environ.get(&#39;PULSAR_TOPIC&#39;)</strong></pre><pre>client = pulsar.Client(<strong>pulsar_url</strong>)</pre><pre>producer = client.create_producer(<br>    <strong>topic</strong>,<br>    block_if_queue_full=True,<br>    batching_enabled=True,<br>    batching_max_publish_delay_ms=10)</pre><pre>def producer_callback(res, msg_id):<br>    print(f&quot;message published {msg_id}&quot;)</pre><pre>i = 0<br>while i &lt;1000:<br>    producer.send_async(<br>        f&quot;Hello-{i}&quot;.encode(&#39;utf-8&#39;),<br>        producer_callback)<br>    i+=1</pre><p>To test the code locally, I export PULSAR_URL and TOPIC on my current local env.</p><pre><strong>export PULSAR_URL=&#39;pulsar://10.0.0.36:6650&#39;<br>export PULSAR_TOPIC=&#39;persistent://public/default/my-topic1&#39;<br>python test_producer.py</strong><br><strong>kubectl exec -n sn-platform my-broker-0 -- bin/pulsar-admin topics stats public/default/my-topic1</strong><br>Defaulted container &quot;pulsar-broker&quot; out of: pulsar-broker, init-sysctl (init)<br>{<br>  &quot;msgRateIn&quot; : 0.0,<br>  &quot;msgThroughputIn&quot; : 0.0,<br>  &quot;msgRateOut&quot; : 0.0,<br>  &quot;msgThroughputOut&quot; : 0.0,<br>  <strong>&quot;bytesInCounter&quot; : 44763,<br>  &quot;msgInCounter&quot; : 3000,</strong><br>  &quot;bytesOutCounter&quot; : 0,<br>  &quot;msgOutCounter&quot; : 0,<br>  &quot;averageMsgSize&quot; : 0.0,<br>  &quot;msgChunkPublished&quot; : false,<br>  &quot;storageSize&quot; : 14921,<br>  &quot;backlogSize&quot; : 0,<br>  &quot;offloadedStorageSize&quot; : 0,<br>  &quot;lastOffloadLedgerId&quot; : 0,<br>  &quot;lastOffloadSuccessTimeStamp&quot; : 0,<br>  &quot;lastOffloadFailureTimeStamp&quot; : 0,<br>  &quot;publishers&quot; : [ ],<br>  &quot;waitingPublishers&quot; : 0,<br>  &quot;subscriptions&quot; : { },<br>  &quot;replication&quot; : { },<br>  &quot;deduplicationStatus&quot; : &quot;Disabled&quot;,<br>  &quot;nonContiguousDeletedMessagesRanges&quot; : 0,<br>  &quot;nonContiguousDeletedMessagesRangesSerializedSize&quot; : 0,<br>  &quot;compaction&quot; : {<br>    &quot;lastCompactionRemovedEventCount&quot; : 0,<br>    &quot;lastCompactionSucceedTimestamp&quot; : 0,<br>    &quot;lastCompactionFailedTimestamp&quot; : 0,<br>    &quot;lastCompactionDurationTimeInMills&quot; : 0<br>  }<br>}</pre><p>Rebuild the image with a new tag.</p><pre><strong>docker buildx build --platform linux/amd64 . -t yuwsung1/pulsar-python-producer:v0.2</strong><br><strong>docker push yuwsung1/pulsar-python-producer:v0.2</strong></pre><p>Note that the v2 will need PULSAR_URL and PULSAR_TOPIC ingested into the producer pod to work. The following are the deployment and configmap.</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: pulsar-producer-config<br>data:<br>  pulsar_url: &quot;pulsar://10.0.0.36:6650&quot;<br>  topic: &quot;my-topic1&quot;<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: my-producer<br>spec:<br>  selector:<br>    matchLabels:<br>      app: my-producer<br>  replicas: 1<br>  template:<br>    metadata:<br>      labels:<br>        app: my-producer<br>    spec:<br>      containers:<br>      - name: pulsar-producer<br>        image: yuwsung1/pulsar-python-producer:v0.2<br>        resources:<br>          limits:<br>            cpu: &quot;500m&quot;<br>            memory: &quot;128Mi&quot;<br>        env:<br>          - name: PULSAR_URL<br>            valueFrom:<br>              configMapKeyRef:<br>                name: pulsar-producer-config<br>                key: pulsar_url<br>          - name: PULSAR_TOPIC<br>            valueFrom:<br>              configMapKeyRef:<br>                name: pulsar-producer-config<br>                key: topic</pre><p>Use kubectl to deploy this configmap and pod, then check the topic stats.</p><pre><strong>kubectl apply -f pulsar-producer.yaml</strong><br><strong>kubectl exec -n sn-platform my-broker-0 -- bin/pulsar-admin topics stats public/default/my-topic1</strong><br>Defaulted container &quot;pulsar-broker&quot; out of: pulsar-broker, init-sysctl (init)<br>{<br>  &quot;msgRateIn&quot; : 0.0,<br>  &quot;msgThroughputIn&quot; : 0.0,<br>  &quot;msgRateOut&quot; : 0.0,<br>  &quot;msgThroughputOut&quot; : 0.0,<br>  <strong>&quot;bytesInCounter&quot; : 59684,<br>  &quot;msgInCounter&quot; : 4000,</strong><br>  &quot;bytesOutCounter&quot; : 0,<br>  &quot;msgOutCounter&quot; : 0,<br>  &quot;averageMsgSize&quot; : 0.0,<br>  &quot;msgChunkPublished&quot; : false,<br>  &quot;storageSize&quot; : 14921,<br>  &quot;backlogSize&quot; : 0,<br>  &quot;offloadedStorageSize&quot; : 0,<br>  &quot;lastOffloadLedgerId&quot; : 0,<br>  &quot;lastOffloadSuccessTimeStamp&quot; : 0,<br>  &quot;lastOffloadFailureTimeStamp&quot; : 0,<br>  &quot;publishers&quot; : [ ],<br>  &quot;waitingPublishers&quot; : 0,<br>  &quot;subscriptions&quot; : { },<br>  &quot;replication&quot; : { },<br>  &quot;deduplicationStatus&quot; : &quot;Disabled&quot;,<br>  &quot;nonContiguousDeletedMessagesRanges&quot; : 0,<br>  &quot;nonContiguousDeletedMessagesRangesSerializedSize&quot; : 0,<br>  &quot;compaction&quot; : {<br>    &quot;lastCompactionRemovedEventCount&quot; : 0,<br>    &quot;lastCompactionSucceedTimestamp&quot; : 0,<br>    &quot;lastCompactionFailedTimestamp&quot; : 0,<br>    &quot;lastCompactionDurationTimeInMills&quot; : 0<br>  }<br>}</pre><p>Now we can follow the same steps to create a consumer image and deployment. I will skip the steps in this tutorial, but you can find the consumer codes in my <a href="https://github.com/yuweisung/pulsa-python">github repo</a>.</p><p>Next part, we will discuss how to use argocd to migrate consumer/producer and upgrade pulsar operator. Stay tune.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd030ac1b7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StreamNative Pulsar Operator Tutorial Part 1]]></title>
            <link>https://yuweisung.medium.com/streamnative-pulsar-operator-tutorial-part-1-7fbbbb07397e?source=rss-8b33def5f214------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fbbbb07397e</guid>
            <category><![CDATA[streamnative]]></category>
            <category><![CDATA[pulsar]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[operators]]></category>
            <dc:creator><![CDATA[Yuwei Sung]]></dc:creator>
            <pubDate>Sun, 08 May 2022 21:32:04 GMT</pubDate>
            <atom:updated>2022-05-13T01:26:53.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vjNysJYRlaCyvRDz" /><figcaption>Photo by <a href="https://unsplash.com/@jamesamolnar?utm_source=medium&amp;utm_medium=referral">James A. Molnar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the article, I demo how to use StreamNative Pulsar operators to deploy a pulsar cluster in my k8s home lab.</p><p>Why use k8s operators? StreamNative provides a good overview of the operator concept <a href="https://docs.streamnative.io/operators/overview">here</a>. StreamNative “open-sources” four operators, zookeeper, bookkeeper, broker, and function mesh, which are wrapped as a helm chart. For a quick start, you can follow the official installation doc <a href="https://docs.streamnative.io/operators/pulsar-operator/pulsar-operator-install">here</a>. This article explores a step-by-step breakdown way to set up the pulsar cluster and observe its capabilities.</p><p>First, instead of “helm install” the chart from the chart repo directly, I fetch the chart and check the details.</p><pre>&gt;<em>helm repo add streamnative </em><a href="https://charts.streamnative.io/"><em>https://charts.streamnative.io</em></a><br>&gt;<em>helm repo update</em><br>&gt;<em>helm fetch streamnative/pulsar-operator --untar</em><br>&gt;<em>cd pulsar-operator </em></pre><p>The command “helm fetch” with the “untar” subcommand will download the chart template to local. Let’s check what is inside the chart.</p><pre>&gt;<em>cat Chart.yaml</em><br>apiVersion: v1<br>appVersion: 0.9.4<br>description: Apache Pulsar Operators Helm chart for Kubernetes<br>home: <a href="https://streamnative.io/">https://streamnative.io</a><br>icon: <a href="http://pulsar.apache.org/img/pulsar.svg">http://pulsar.apache.org/img/pulsar.svg</a><br>kubeVersion: <strong>&#39;&gt;= 1.16.0-0 &lt; 1.24.0-0&#39;</strong><br>maintainers:<br>- email: <a href="/service/mailto:support@streamnative.io">support@streamnative.io</a><br>  name: StreamNative Support<br>name: pulsar-operator<br>sources:<br>- <a href="https://github.com/streamnative/pulsar-operators">https://github.com/streamnative/pulsar-operators</a><br>version: 0.10.0</pre><p>From the above, the current chart supports k8s version 1.16 to 1.23. My homelab k8s is 1.24.0. If I run the “helm install” directly from the remote chart repo, the installation will stop at the k8s version check.</p><pre>&gt;<em>helm install sn-operator -n test streamnative/pulsar-operator</em><br><strong>Error: INSTALLATION FAILED: chart requires kubeVersion: &gt;= 1.16.0-0 &lt; 1.24.0-0 which is incompatible with Kubernetes v1.24.0</strong></pre><p>To bypass this, I modify the kubeVersion range to ‘&gt;=1.16.0–0 &lt; 1.25.0–0’. This is YMMV as k8s 1.24 is just released days ago. Give Streamnative team some time to test.</p><p>After changing the Chart.yaml, regular helm users go through the default values.yaml file as documentation. This values file is pretty straightforward. It describes what operators you can install. There are zookeeper-operator, bookkeeper-operator, and pulsar-operator (broker/proxy). Then, it tells the image repo location and tags, followed by the operator details like cluster role/role, service account, and operator resource limits and requests. <br>I keep the default in the “values.yaml”. I will come back to modify those in a more restrictive env, e.g., CRD role vs. cluster role bindings.</p><p>After reviewing the values and changing the chart support kubeVersion, I “helm install” the operator in the sn-operator namespace from my local chart.</p><pre>&gt;<em>kubectl create namespace sn-operator</em><br>&gt;<em>helm install -n sn-operator pulsar-operator .</em> <br>&gt;<em>kubectl get all -n sn-operator</em><br>NAME                                                                READY   STATUS    RESTARTS   AGE<br>pod/pulsar-operator-bookkeeper-controller-manager-9c596465-h8nbh    1/1     Running   0          16h<br>pod/pulsar-operator-pulsar-controller-manager-6f8699ffc-gr989       1/1     Running   0          16h<br>pod/pulsar-operator-zookeeper-controller-manager-7b54b76c79-rsm6t   1/1     Running   0          16h</pre><pre>NAME                                                            READY   UP-TO-DATE   AVAILABLE   AGE<br>deployment.apps/pulsar-operator-bookkeeper-controller-manager   1/1     1            1           16h<br>deployment.apps/pulsar-operator-pulsar-controller-manager       1/1     1            1           16h<br>deployment.apps/pulsar-operator-zookeeper-controller-manager    1/1     1            1           16h</pre><pre>NAME                                                                      DESIRED   CURRENT   READY   AGE<br>replicaset.apps/pulsar-operator-bookkeeper-controller-manager-9c596465    1         1         1       16h<br>replicaset.apps/pulsar-operator-pulsar-controller-manager-6f8699ffc       1         1         1       16h<br>replicaset.apps/pulsar-operator-zookeeper-controller-manager-7b54b76c79   1         1         1       16h</pre><p>If you check your k8s API resources, you will find all the API created.</p><pre>&gt;<em>kubectl api-resources | grep pulsar</em><br>pulsarbrokers                     pb,broker         pulsar.streamnative.io/v1alpha1        true         PulsarBroker<br>pulsarconnections                 pconn             pulsar.streamnative.io/v1alpha1        true         PulsarConnection<br>pulsarnamespaces                  pns               pulsar.streamnative.io/v1alpha1        true         PulsarNamespace<br>pulsarpermissions                 ppermission       pulsar.streamnative.io/v1alpha1        true         PulsarPermission<br>pulsarproxies                     pp,proxy          pulsar.streamnative.io/v1alpha1        true         PulsarProxy<br>pulsartenants                     ptenant           pulsar.streamnative.io/v1alpha1        true         PulsarTenant<br>pulsartopics                      ptopic            pulsar.streamnative.io/v1alpha1        true         PulsarTopic</pre><p>As shown above, there are three controllers/operators, and each handles different “kinds” of clusters. You can use the API to create Topic,Tenant, permissions. Like the standard k8s controllers, deployment, for example, we tell the controller what we want by feeding the cluster definitions. In a regular k8s deployment, you put all kinds of components in a yaml file and use “apply” or “create” to create pods, services, configmap, and others. You can put zookeeper, bookkeeper, and broker cluster definitions in a single yaml file, then deploy them in one shot. In order to understand and troubleshoot the deployment, I break it down into three steps, zookeeper, bookkeeper, then broker. If you want to understand the dependencies among the three, check out Sijie Guo’s <a href="https://www.youtube.com/watch?v=1RQSot5tTuU&amp;t=112s">TGIP Youtube channel.</a> The sequence is zookeeper, bookkeeper, broker, then others.</p><p>The following is the ZooKeeperCluster definition that the zookeeper controller/operator will take to deploy a zookeeper cluster. It is very similar to a deployment. It defines the image location, version, replicas, resources, and persistent disk properties. There should be other properties like JVM flags for tuning. I will discuss this later as we focus on getting a running cluster, and the operator should help make the extra configs updated automatically.</p><pre>---<br>apiVersion: zookeeper.streamnative.io/v1alpha1<br>kind: ZooKeeperCluster<br>metadata:<br>  name: my<br>  namespace: sn-platform<br>spec:<br>  image: streamnative/pulsar:2.9.2.15<br>  replicas: 3<br>  pod:<br>    resources:<br>      requests:<br>        cpu: &quot;50m&quot;<br>        memory: &quot;256Mi&quot;<br>  persistence:<br>    reclaimPolicy: Retain<br>    data:<br>      accessModes:<br>      - ReadWriteOnce<br>      resources:<br>        requests:<br>          storage: &quot;10Gi&quot;<br>    dataLog:<br>      accessModes:<br>      - ReadWriteOnce<br>      resources:<br>        requests:<br>          storage: &quot;2Gi&quot;</pre><p>Let’s apply this file and see what happens.</p><pre>&gt;<em>kubectl apply -f zk-cluster.yaml</em><br>zookeepercluster.zookeeper.streamnative.io/my created<br>&gt;<em>kubectl get pod -n sn-platform -w</em><br>NAME      READY   STATUS    RESTARTS   AGE<br>my-zk-0   1/1     Running   0          25s<br>my-zk-1   1/1     Running   0          25s<br>my-zk-2   1/1     Running   0          25s<br>&gt;kubectl get svc -n sn-platform<br>NAME             TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)                                        AGE<br>my-zk            ClusterIP   10.104.64.179   &lt;none&gt;        2181/TCP,8000/TCP,9990/TCP                     42s<br>my-zk-headless   ClusterIP   None            &lt;none&gt;        2181/TCP,2888/TCP,3888/TCP,8000/TCP,9990/TCP   42s</pre><p>Let’s check the zookeeper controller log and what’s going on in there.</p><pre>&gt;kubectl logs -n sn-ops pulsar-operator-zookeeper-controller-manager-7b54b76c79-rsm6t</pre><pre>{&quot;severity&quot;:&quot;info&quot;,&quot;timestamp&quot;:&quot;2022-05-11T02:47:07Z&quot;,&quot;logger&quot;:&quot;controllers.ZooKeeperCluster&quot;,&quot;message&quot;:&quot;Reconciling ZooKeeperCluster&quot;,&quot;Request.Namespace&quot;:&quot;sn-platform&quot;,&quot;Request.Name&quot;:&quot;my&quot;}</pre><pre>{&quot;severity&quot;:&quot;info&quot;,&quot;timestamp&quot;:&quot;2022-05-11T02:47:07Z&quot;,&quot;logger&quot;:&quot;controllers.ZooKeeperCluster&quot;,&quot;message&quot;:&quot;Updating an existing ZooKeeper StatefulSet&quot;,&quot;StatefulSet.Namespace&quot;:&quot;sn-platform&quot;,&quot;StatefulSet.Name&quot;:&quot;my-zk&quot;}</pre><pre>{&quot;severity&quot;:&quot;debug&quot;,&quot;timestamp&quot;:&quot;2022-05-11T02:47:07Z&quot;,&quot;logger&quot;:&quot;controller&quot;,&quot;message&quot;:&quot;Successfully Reconciled&quot;,&quot;reconcilerGroup&quot;:&quot;zookeeper.streamnative.io&quot;,&quot;reconcilerKind&quot;:&quot;ZooKeeperCluster&quot;,&quot;controller&quot;:&quot;zookeepercluster&quot;,&quot;name&quot;:&quot;my&quot;,&quot;namespace&quot;:&quot;sn-platform&quot;}</pre><pre>{&quot;severity&quot;:&quot;info&quot;,&quot;timestamp&quot;:&quot;2022-05-11T02:47:07Z&quot;,&quot;logger&quot;:&quot;controllers.ZooKeeperCluster&quot;,&quot;message&quot;:&quot;Reconciling ZooKeeperCluster&quot;,&quot;Request.Namespace&quot;:&quot;sn-platform&quot;,&quot;Request.Name&quot;:&quot;my&quot;}</pre><pre>{&quot;severity&quot;:&quot;info&quot;,&quot;timestamp&quot;:&quot;2022-05-11T02:47:07Z&quot;,&quot;logger&quot;:&quot;controllers.ZooKeeperCluster&quot;,&quot;message&quot;:&quot;Updating an existing ZooKeeper StatefulSet&quot;,&quot;StatefulSet.Namespace&quot;:&quot;sn-platform&quot;,&quot;StatefulSet.Name&quot;:&quot;my-zk&quot;}</pre><pre>{&quot;severity&quot;:&quot;debug&quot;,&quot;timestamp&quot;:&quot;2022-05-11T02:47:07Z&quot;,&quot;logger&quot;:&quot;controller&quot;,&quot;message&quot;:&quot;Successfully Reconciled&quot;,&quot;reconcilerGroup&quot;:&quot;zookeeper.streamnative.io&quot;,&quot;reconcilerKind&quot;:&quot;ZooKeeperCluster&quot;,&quot;controller&quot;:&quot;zookeepercluster&quot;,&quot;name&quot;:&quot;my&quot;,&quot;namespace&quot;:&quot;sn-platform&quot;}</pre><pre>{&quot;severity&quot;:&quot;info&quot;,&quot;timestamp&quot;:&quot;2022-05-11T02:47:07Z&quot;,&quot;logger&quot;:&quot;controllers.ZooKeeperCluster&quot;,&quot;message&quot;:&quot;Reconciling ZooKeeperCluster&quot;,&quot;Request.Namespace&quot;:&quot;sn-platform&quot;,&quot;Request.Name&quot;:&quot;my&quot;}</pre><pre>{&quot;severity&quot;:&quot;info&quot;,&quot;timestamp&quot;:&quot;2022-05-11T02:47:07Z&quot;,&quot;logger&quot;:&quot;controllers.ZooKeeperCluster&quot;,&quot;message&quot;:&quot;Updating an existing ZooKeeper StatefulSet&quot;,&quot;StatefulSet.Namespace&quot;:&quot;sn-platform&quot;,&quot;StatefulSet.Name&quot;:&quot;my-zk&quot;}</pre><p>The zookeeper controller is running a reconcile loop which keeps checking the “my” ZooKeeperCluster status in sn-platform namespace. This is a recommended <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/operator/">operator design pattern</a>. This operator pod log is handy to troubleshoot pulsar deployment.</p><p>The next component is the bookkeeper cluster. Following the same pattern, I define the BookKeeperCluster kind like the following.</p><pre>---<br>apiVersion: bookkeeper.streamnative.io/v1alpha1<br>kind: BookKeeperCluster<br>metadata:<br>  name: my<br>  namespace: sn-platform<br>spec:<br>  image: streamnative/pulsar:2.9.2.15<br>  replicas: 3<br>  pod:<br>    resources:<br>      requests:<br>        cpu: &quot;200m&quot;<br>        memory: &quot;256Mi&quot;<br>  storage:<br>    reclaimPolicy: Retain<br>    journal:<br>      numDirsPerVolume: 1<br>      numVolumes: 1<br>      volumeClaimTemplate:<br>        accessModes:<br>        - ReadWriteOnce<br>        resources:<br>          requests:<br>            storage: &quot;8Gi&quot;<br>    ledger:<br>      numDirsPerVolume: 1<br>      numVolumes: 1<br>      volumeClaimTemplate:<br>        accessModes:<br>        - ReadWriteOnce<br>        resources:<br>          requests:<br>            storage: &quot;16Gi&quot;<br>  zkServers: my-zk-headless:2181</pre><p>Note that “zkServers” is required in this yaml file, and it should point to the headless service (reaching all three zkServers).</p><pre>&gt;<em>kubectl apply -f bk-cluster.yaml</em><br>bookkeepercluster.bookkeeper.streamnative.io/my created<br>&gt;<em>kubectl get pod -n sn-platform</em><br>NAME                    READY   STATUS    RESTARTS   AGE<br>my-bk-0                 1/1     Running   0          90s<br>my-bk-1                 1/1     Running   0          90s<br>my-bk-2                 1/1     Running   0          90s<br>my-bk-auto-recovery-0   1/1     Running   0          48s<br>my-zk-0                 1/1     Running   0          4m51s<br>my-zk-1                 1/1     Running   0          4m51s<br>my-zk-2                 1/1     Running   0          4m51s</pre><p>You can follow the same command to find out what the bookkeeper operator is doing behind the scenes.</p><pre>&gt;kubectl logs -n sn-ops pulsar-operator-bookkeeper-controller-manager-9c596465-h8nbh</pre><pre>W0512 11:45:15.235940       1 warnings.go:67] policy/v1beta1 PodDisruptionBudget is deprecated in v1.21+, unavailable in v1.25+; use policy/v1 PodDisruptionBudget</pre><pre>{&quot;severity&quot;:&quot;info&quot;,&quot;timestamp&quot;:&quot;2022-05-12T11:47:27Z&quot;,&quot;logger&quot;:&quot;controllers.BookKeeperCluster&quot;,&quot;message&quot;:&quot;Reconciling BookKeeperCluster&quot;,&quot;Request.Namespace&quot;:&quot;sn-platform&quot;,&quot;Request.Name&quot;:&quot;my&quot;}</pre><pre>{&quot;severity&quot;:&quot;info&quot;,&quot;timestamp&quot;:&quot;2022-05-12T11:47:27Z&quot;,&quot;logger&quot;:&quot;controllers.BookKeeperCluster&quot;,&quot;message&quot;:&quot;Updating the status for the BookKeeperCluster&quot;,&quot;Namespace&quot;:&quot;sn-platform&quot;,&quot;Name&quot;:&quot;my&quot;,&quot;Status&quot;:{&quot;observedGeneration&quot;:4,&quot;replicas&quot;:4,&quot;readyReplicas&quot;:4,&quot;updatedReplicas&quot;:4,&quot;labelSelector&quot;:&quot;cloud.streamnative.io/app=pulsar,cloud.streamnative.io/cluster=my,cloud.streamnative.io/component=bookie&quot;,&quot;conditions&quot;:[{&quot;type&quot;:&quot;AutoRecovery&quot;,&quot;status&quot;:&quot;True&quot;,&quot;reason&quot;:&quot;Deploy&quot;,&quot;message&quot;:&quot;Ready&quot;,&quot;lastTransitionTime&quot;:&quot;2022-05-08T19:58:26Z&quot;},{&quot;type&quot;:&quot;Bookie&quot;,&quot;status&quot;:&quot;True&quot;,&quot;reason&quot;:&quot;Ready&quot;,&quot;message&quot;:&quot;Bookies are ready&quot;,&quot;lastTransitionTime&quot;:&quot;2022-05-09T00:34:12Z&quot;},{&quot;type&quot;:&quot;Initialization&quot;,&quot;status&quot;:&quot;True&quot;,&quot;reason&quot;:&quot;Initialization&quot;,&quot;message&quot;:&quot;Initialization succeeded&quot;,&quot;lastTransitionTime&quot;:&quot;2022-05-08T19:57:43Z&quot;},{&quot;type&quot;:&quot;Ready&quot;,&quot;status&quot;:&quot;True&quot;,&quot;reason&quot;:&quot;Ready&quot;,&quot;lastTransitionTime&quot;:&quot;2022-05-09T00:34:12Z&quot;}]}}</pre><pre>{&quot;severity&quot;:&quot;debug&quot;,&quot;timestamp&quot;:&quot;2022-05-12T11:47:27Z&quot;,&quot;logger&quot;:&quot;controller&quot;,&quot;message&quot;:&quot;Successfully Reconciled&quot;,&quot;reconcilerGroup&quot;:&quot;bookkeeper.streamnative.io&quot;,&quot;reconcilerKind&quot;:&quot;BookKeeperCluster&quot;,&quot;controller&quot;:&quot;bookkeepercluster&quot;,&quot;name&quot;:&quot;my&quot;,&quot;namespace&quot;:&quot;sn-platform&quot;}</pre><pre>W0512 11:49:18.419391       1 warnings.go:67] autoscaling/v2beta2 HorizontalPodAutoscaler is deprecated in v1.23+, unavailable in v1.26+; use autoscaling/v2 HorizontalPodAutoscaler</pre><pre>W0512 11:52:35.237812       1 warnings.go:67] policy/v1beta1 PodDisruptionBudget is deprecated in v1.21+, unavailable in v1.25+; use policy/v1 PodDisruptionBudget</pre><pre>W0512 11:57:06.421507       1 warnings.go:67] autoscaling/v2beta2 HorizontalPodAutoscaler is deprecated in v1.23+, unavailable in v1.26+; use autoscaling/v2 HorizontalPodAutoscaler</pre><pre>W0512 11:58:43.240049       1 warnings.go:67] policy/v1beta1 PodDisruptionBudget is deprecated in v1.21+, unavailable in v1.25+; use policy/v1 PodDisruptionBudget</pre><pre>W0512 12:04:06.423448       1 warnings.go:67] autoscaling/v2beta2 HorizontalPodAutoscaler is deprecated in v1.23+, unavailable in v1.26+; use autoscaling/v2 HorizontalPodAutoscaler</pre><pre>W0512 12:05:03.242609       1 warnings.go:67] policy/v1beta1 PodDisruptionBudget is deprecated in v1.21+, unavailable in v1.25+; use policy/v1 PodDisruptionBudget</pre><pre>W0512 12:09:08.425304       1 warnings.go:67] autoscaling/v2beta2 HorizontalPodAutoscaler is deprecated in v1.23+, unavailable in v1.26+; use autoscaling/v2 HorizontalPodAutoscaler</pre><pre>W0512 12:14:15.245078       1 warnings.go:67] policy/v1beta1 PodDisruptionBudget is deprecated in v1.21+, unavailable in v1.25+; use policy/v1 PodDisruptionBudget</pre><pre>W0512 12:18:47.427470       1 warnings.go:67] autoscaling/v2beta2 HorizontalPodAutoscaler is deprecated in v1.23+, unavailable in v1.26+; use autoscaling/v2 HorizontalPodAutoscaler</pre><pre>W0512 12:19:30.247840       1 warnings.go:67] policy/v1beta1 PodDisruptionBudget is deprecated in v1.21+, unavailable in v1.25+; use policy/v1 PodDisruptionBudget</pre><pre>W0512 12:25:04.249159       1 warnings.go:67] policy/v1beta1 PodDisruptionBudget is deprecated in v1.21+, unavailable in v1.25+; use policy/v1 PodDisruptionBudget</pre><pre>W0512 12:25:13.430394       1 warnings.go:67] autoscaling/v2beta2 HorizontalPodAutoscaler is deprecated in v1.23+, unavailable in v1.26+; use autoscaling/v2 HorizontalPodAutoscaler</pre><p>There are a bunch of warnings complaining about api deprecated. This is normal because I have the current version (v1.24.0). Kube1.24.0 has <a href="https://kubernetes.io/blog/2022/04/07/upcoming-changes-in-kubernetes-1-24/">many big changes</a>.</p><p>The next component is the broker cluster. The following is the PulsarBroker yaml file. From the file, you can see that broker also depends on zkServer. Note that I add “config.custom” in the descriptor.</p><pre>---<br>apiVersion: pulsar.streamnative.io/v1alpha1<br>kind: PulsarBroker<br>metadata:<br>  name: my<br>  namespace: sn-platform<br>spec:<br>  image: streamnative/pulsar:2.9.2.15<br>  pod:<br>    resources:<br>      requests:<br>        cpu: 200m<br>        memory: 256Mi<br>    terminationGracePeriodSeconds: 30<br>  config:<br>    custom:<br>      webSocketServiceEnabled: &quot;true&quot;<br>  replicas: 2<br>  zkServers: my-zk-headless:2181</pre><p>Like zookeeper and bookkeeper clusters, creating a broker cluster is the same as creating standard k8s objects. I used ‘kubectl get pod -n &lt;namespace&gt; -w’ to watch the sequence of pod creation. This is helpful to understand the pulsar component dependencies. I skipped the operator log in this article. You can run a similar command to trace the controller log.</p><pre>&gt;<em>kubectl apply -f br-cluster.yaml</em><br>pulsarbroker.pulsar.streamnative.io/my created<br>&gt;<em>kubectl get pod -n sn-platform -w</em><br>NAME                            READY   STATUS      RESTARTS   AGE<br>my-bk-0                         1/1     Running     0          2m11s<br>my-bk-1                         1/1     Running     0          2m11s<br>my-bk-2                         1/1     Running     0          2m11s<br>my-bk-auto-recovery-0           1/1     Running     0          89s<br>my-broker-metadata-init-gghqc   0/1     Completed   0          6s<br>my-zk-0                         1/1     Running     0          5m32s<br>my-zk-1                         1/1     Running     0          5m32s<br>my-zk-2                         1/1     Running     0          5m32s<br>my-broker-metadata-init-gghqc   0/1     Completed   0          7s<br>my-broker-metadata-init-gghqc   0/1     Completed   0          7s<br>my-broker-0                     0/1     Pending     0          0s<br>my-broker-1                     0/1     Pending     0          0s<br>my-broker-0                     0/1     Pending     0          0s<br>my-broker-1                     0/1     Pending     0          0s<br>my-broker-1                     0/1     Init:0/1    0          0s<br>my-broker-0                     0/1     Init:0/1    0          0s<br>my-broker-metadata-init-gghqc   0/1     Terminating   0          8s<br>my-broker-metadata-init-gghqc   0/1     Terminating   0          8s<br>my-broker-0                     0/1     Init:0/1      0          0s<br>my-broker-1                     0/1     Init:0/1      0          0s<br>my-broker-1                     0/1     PodInitializing   0          1s<br>my-broker-0                     0/1     PodInitializing   0          1s<br>my-broker-1                     0/1     Running           0          2s<br>my-broker-0                     0/1     Running           0          2s<br>my-broker-0                     0/1     Running           0          10s<br>my-broker-1                     0/1     Running           0          10s<br>my-broker-0                     1/1     Running           0          40s<br>my-broker-1                     1/1     Running           0          40s</pre><p>When all pods are running and READY, I check the services and found all services are ClusterIP. This assumes that all producer and consumer workloads are inside the K8S cluster. In order to test the traffic, I want a LoadBalancer from machines in my home lab but external of the K8S cluster. So the final component in this article is proxy.</p><pre>---<br>apiVersion: pulsar.streamnative.io/v1alpha1<br>kind: PulsarProxy<br>metadata:<br>    name: my<br>    namespace: sn-platform<br>spec:<br>    brokerAddress: my-broker-headless <br>    dnsNames: []<br>    #webSocketServiceEnabled: true<br>    image: streamnative/pulsar:2.9.2.15<br>    config:<br>      tls:<br>        enabled: false <br>    issuerRef:<br>      name: &quot;&quot;<br>    pod:<br>      resources:<br>        requests:<br>          cpu: 200m<br>          memory: 256Mi<br>    replicas: 1</pre><p>Proxy is a bit tricky because TLS is enabled in default which makes sense as it is the external gateway to connect to the pulsar cluster. In this article, I turn off TLS on all components for simplicity. I will discuss enabling TLS using the operator in the next article.</p><pre>&gt;<em>kubectl apply -f px-cluster.yaml</em><br>pulsarproxy.pulsar.streamnative.io/my created<br>&gt;<em>kubectl get pod -n sn-platform</em><br>NAME                    READY   STATUS    RESTARTS   AGE<br>my-bk-0                 1/1     Running   0          44m<br>my-bk-1                 1/1     Running   0          44m<br>my-bk-2                 1/1     Running   0          44m<br>my-bk-auto-recovery-0   1/1     Running   0          43m<br>my-broker-0             1/1     Running   0          42m<br>my-broker-1             1/1     Running   0          42m<br>my-proxy-0              1/1     Running   0          57s<br>my-zk-0                 1/1     Running   0          47m<br>my-zk-1                 1/1     Running   0          47m<br>my-zk-2                 1/1     Running   0          47m<br>&gt;kubectl get svc -n sn-platform<br>NAME                           TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)                                        AGE<br>my-bk                          ClusterIP      10.104.212.43   &lt;none&gt;        3181/TCP,8000/TCP                              44m<br>my-bk-auto-recovery-headless   ClusterIP      None            &lt;none&gt;        3181/TCP,8000/TCP                              44m<br>my-bk-headless                 ClusterIP      None            &lt;none&gt;        3181/TCP,8000/TCP                              44m<br>my-broker                      ClusterIP      10.99.107.224   &lt;none&gt;        6650/TCP,8080/TCP                              41m<br>my-broker-headless             ClusterIP      None            &lt;none&gt;        6650/TCP,8080/TCP                              41m<br>my-proxy-external              LoadBalancer   10.109.250.31   10.0.0.36     6650:32751/TCP,8080:30322/TCP                  33s<br>my-proxy-headless              ClusterIP      None            &lt;none&gt;        6650/TCP,8080/TCP                              33s<br>my-zk                          ClusterIP      10.104.64.179   &lt;none&gt;        2181/TCP,8000/TCP,9990/TCP                     47m<br>my-zk-headless                 ClusterIP      None            &lt;none&gt;        2181/TCP,2888/TCP,3888/TCP,8000/TCP,9990/TCP   47m</pre><p>Proxy automatically gets my external LoadBalancer IP (10.0.0.36). <br>In part 2, let’s write simple python test codes to produce and consume messages. Also, find out how we change component behaviors using operators, e.g. jvm tuning and mTLS.<br>In part 3, install the function mesh operator and simple functions.<br>In part 4, Pulsar Observability.</p><p>Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fbbbb07397e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>