<?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 Dounpct on Medium]]></title>
        <description><![CDATA[Stories by Dounpct on Medium]]></description>
        <link>https://medium.com/@dounpct?source=rss-253b52b8830------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NA3wrsSDvYmfRQ_ntoktrw.png</url>
            <title>Stories by Dounpct on Medium</title>
            <link>https://medium.com/@dounpct?source=rss-253b52b8830------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:05:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dounpct/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[Solve problem DBeaver, openssl s_client cannot terminate ssl cert on java application but web…]]></title>
            <link>https://dounpct.medium.com/solve-problem-dbeaver-openssl-s-client-cannot-terminate-ssl-cert-on-java-application-but-web-90b70f5721b6?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b70f5721b6</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 14:08:57 GMT</pubDate>
            <atom:updated>2024-10-12T14:08:57.376Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solve problem DBeaver, openssl s_client cannot terminate ssl cert on java application but web browser can</h3><p>Few days ago My devops lead invite me for case that Devops team have update ssl certificate. They already test after update ssl certificate with browser before a week that old certificate will expired. At that time most of user can open and access to web browser and ok browser show secure connection.</p><p>I need to tell story. This application belong to Analytic team and handle by DevOps of Analytic team. One month ago no one left in DevOps of Analytic team before they left they short hand over to My DevOps team. If you are techies this is hardest for do anything for application or system or upgrade but often happen with everyone and we can’t avoid. So we need to help together to move on and support.</p><p>So issue is web browser can terminate ssl certificate and show secure connection but DBeaver for query PrestoDB error with “unable to find valid certifaction path to requested target” or “unable to get local issuer certificate” or “unable to verify the first certificate”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*FrTaHJ5nAs1llsKMI8LXmw.png" /></figure><p><strong>Day1</strong></p><p>After I got problem from my DevOps lead. I start to check with browser and ok It can show secure connection.</p><p>I still don’t have information to connect database with DBeaver. I try to test with <a href="https://www.ssllabs.com/ssltest">https://www.ssllabs.com/ssltest</a> but it can not resolve because domain name map internal ip.</p><ul><li>I start with request for server key ca-bundled and private key.</li><li>I checking with script.</li></ul><pre>#!/bin/bash<br><br>cat $1 $2 &gt; tls.crt<br>cp $3 tls.key<br><br><br>openssl x509 -in tls.crt -text -noout<br>openssl rsa -in tls.key -check<br><br># Store modulus of tls.crt<br>crt_modulus=$(openssl x509 -noout -modulus -in tls.crt | openssl md5)<br><br># Store modulus of tls.key<br>key_modulus=$(openssl rsa -noout -modulus -in tls.key | openssl md5)<br><br># Compare the results<br>if [ &quot;$crt_modulus&quot; = &quot;$key_modulus&quot; ]; then<br>    echo &quot;Match: Private key corresponds to the certificate&quot;<br>else<br>    echo &quot;No match: Private key does not correspond to the certificate&quot;<br>fi</pre><pre>./genkey.bash STAR_tdg-analytics-platform_io_2024.crt STAR_tdg-analytics-platform_io_2024.crt private_key.txt</pre><ul><li>Result</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0UdqwzVTve3-4_59dbJOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkdzqSgK5q4QRCnepn4M9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*L7zuFwKdZMuK7Jv3Qn0_Pw.png" /></figure><ul><li>It mean server ca-bundle have valid for date and private key ok and match with server and ca-bundle.</li><li>My devops lead try to re update and redeploy ssl certificate but user still same problem.</li><li>I try to search and found that why Browser can terminate but other tools may can’t. refer to <a href="https://pavolkutaj.medium.com/unable-to-verify-the-first-certificate-with-openssl-47eecb652a9b">https://pavolkutaj.medium.com/unable-to-verify-the-first-certificate-with-openssl-47eecb652a9b</a></li><li>I try to check with openssl s_client</li></ul><pre>openssl s_client -connect &lt;internal-domain.io&gt;:443 -servername &lt;internal-domain.io&gt;</pre><ul><li>Result have error same like show with DBeaver app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Jq0w5h5lGtSkKEBe0ah7fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jzyzl5JXVKUxeMnmsekc5A.png" /></figure><ul><li>So I test with -CAfile STAR_tdg-analytics-platform_io_2024.crt</li></ul><pre>openssl s_client -connect &lt;internal-domain.io&gt;:443 -servername &lt;internal-domain.io&gt; -CAfile STAR_tdg-analytics-platform_io_2024.crt</pre><ul><li>Result still error.</li><li>Now I think ca-bundle or (intermediate and root) may be wrong.</li><li>I try to download intermediate and root ca file from <a href="https://support.sectigo.com/articles/Knowledge/Sectigo-Intermediate-Certificates">https://support.sectigo.com/articles/Knowledge/Sectigo-Intermediate-Certificates</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*WiuqU7P1jY04g6ICD1RP7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*cH6yKs7BscAO78mboQdBUw.png" /></figure><ul><li>I create new ca-bundle.</li></ul><pre>cp SHA-2\ Root\ \ USERTrust\ RSA\ Certification\ Authority.crt ca-bundle-fix.crt<br>cat SectigoRSADomainValidationSecureServerCA.crt &gt;&gt; ca-bundle-fix.crt </pre><ul><li>I test again new ca-bundle then result fine.</li></ul><pre>openssl s_client -connect &lt;internal-domain.io&gt;:443 -servername &lt;internal-domain.io&gt; -CAfile ca-bundle-fix.crt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGkz0oAEZvyjb5edtldneg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ch-Lsc9FTj8OzQ1cPvZk0Q.png" /></figure><ul><li>Now I think high possibility that old ca-bundle will wrong or not up to date.</li><li>I test again with old ca-bundle then error</li></ul><pre>openssl verify STAR_tdg-analytics-platform_io_2024.crt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uh4zNMHpJg8AbXzU104oUg.png" /></figure><ul><li>But from new ca-bundle fine.</li></ul><pre>openssl verify ca-bundle-fix.crt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kk1neZ-EG4GYrgAw_uUcMg.png" /></figure><ul><li>I test with more option for old ca-bundle with server then still error.</li></ul><pre>openssl verify -CAfile STAR_tdg-analytics-platform_io_2024.ca-bundle  STAR_tdg-analytics-platform_io_2024.crt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2DYFO90wAZXK8ncpTASOw.png" /></figure><ul><li>But new ca-bundle with server fine.</li></ul><pre>openssl verify -CAfile ca-bundle-fix.crt  STAR_tdg-analytics-platform_io_2024.crt </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xb33SL1DPur4iPcqgIe_xw.png" /></figure><p>Finally I think ca-bundle wrong and I send new ca-bundle to my Devops lead to upgrade ssl certificate.</p><p><strong>Day2</strong></p><ul><li>Devops lead try to update ssl cert but this time error when redeploy to deployment and pod crashloopbackoff.</li><li>We have meeting for pod crashloopbackoff. Devops lead show step to update ssl to secret and redeploy for java application.</li><li>I just know step for update ssl that need to convert from our cert to JKS file.</li></ul><pre>openssl pkcs12 -export -in &lt;server.crt&gt; -inkey key.key -out keystore.p12 -name tdg-analytics-platform -CAfile &lt;new-ca-bunlde&gt; -caname root</pre><pre>keytool -importkeystore -srckeystore keystore.p12 -srcstoretype PKCS12 -destkeystore keystore.jks -deststoretype JKS<br>(this step it will recommend to run:<br>keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.jks -deststoretype pkcs12<br>)</pre><pre>keytool -list -v -keystore keystore.jks</pre><pre>base64 -i keystore.jks &gt; keystore.yaml</pre><pre>cat keystore.yaml</pre><ul><li>Error in log deployment show about “java.io.IOException: Invalid keystore format”.</li><li>I try to remove step recommend so new step will be.</li></ul><pre>openssl pkcs12 -export -in &lt;server.crt&gt; -inkey key.key -out keystore.p12 -name tdg-analytics-platform -CAfile &lt;new-ca-bunlde&gt; -caname root<br>keytool -importkeystore -srckeystore keystore.p12 -srcstoretype PKCS12 -destkeystore keystore.jks -deststoretype JKS<br>keytool -list -v -keystore keystore.jks<br>base64 -i keystore.jks &gt; keystore.yaml<br>cat keystore.yaml</pre><ul><li>Now I can deploy to Deployment and pod running as well.</li></ul><p><strong>Day3</strong></p><ul><li>User tell us that still error.</li><li>I still have same error too with.</li></ul><pre>openssl s_client -connect &lt;internal-domain.io&gt;:443 -servername &lt;internal-domain.io&gt;</pre><ul><li>I try to review again for step to create keystore.jks after a hour. I try many thing but this step is ok.</li></ul><pre># server + new ca-bundle<br>cat STAR_tdg-analytics-platform_io_2024.crt ca-bundle-fix.crt &gt; tls.crt<br>cp private_key.txt tls.key<br><br># no need seprarate -in with -CAfile &lt;new-ca-bunlde&gt;<br>openssl pkcs12 -export -in tls.crt -inkey tls.key -out keystore.p12 -name tdg-analytics-platform -caname root<br>keytool -importkeystore -srckeystore keystore.p12 -srcstoretype PKCS12 -destkeystore keystore.jks -deststoretype JKS<br>keytool -list -v -keystore keystore.jks<br>base64 -i keystore.jks &gt; keystore.yaml<br>cat keystore.yaml</pre><ul><li>Then I test</li></ul><pre>openssl s_client -connect &lt;internal-domain.io&gt;:443 -servername &lt;internal-domain.io&gt;</pre><ul><li>Result fine</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WAI6VPyYncECoZMNIiRACg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pyoNLVAEoQq4nD3RryXSg.png" /></figure><ul><li>OH!!!!! I think old ca-bundle may can use?</li><li>I try old ca-bundle.</li></ul><pre># server + new ca-bundle<br>cat STAR_tdg-analytics-platform_io_2024.crt STAR_tdg-analytics-platform_io_2024.ca-bundle &gt; tls.crt<br>cp private_key.txt tls.key<br><br>openssl pkcs12 -export -in tls.crt -inkey tls.key -out keystore.p12 -name tdg-analytics-platform -caname root<br>keytool -importkeystore -srckeystore keystore.p12 -srcstoretype PKCS12 -destkeystore keystore.jks -deststoretype JKS<br>keytool -list -v -keystore keystore.jks<br>base64 -i keystore.jks &gt; keystore.yaml<br>cat keystore.yaml</pre><blockquote>OH!!!!! result is fine too.</blockquote><blockquote>Now I think problem not because ca-bundle file. but problem with step to create “keystore.jks”</blockquote><ul><li>Now User can connect DBeaver for query PrestoDB</li><li>Problem and issue have been solved.</li></ul><p>Today our issue finish in time. I have great experience in my DevOps skill problem solving so much. Thank you our DevOps team for being and help together.</p><blockquote>Sometime I almost give up to find solution. But when I can clear problem I’m very happy.</blockquote><p>I hope this solution may help some one.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b70f5721b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Investigate memory leak for application on kubernetes]]></title>
            <link>https://dounpct.medium.com/investigate-memory-leak-for-application-on-kubernetes-e68809f1dbbf?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/e68809f1dbbf</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sun, 16 Jun 2024 15:45:59 GMT</pubDate>
            <atom:updated>2024-06-16T16:05:59.386Z</atom:updated>
            <content:encoded><![CDATA[<p>Two week ago Mobile Team have deployed a application to nonprod cluster and need to load test for getting Baseline Throughput(TPS),Response Times(ms) and Error rate.</p><p>When I start load test with developer team then result of load test fine but consume high memory up to 1GB to 4GB and don’t stop until OOM Killed. I think it worst for go live. So I start to investigate why application consume high memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*NFa0lDSyp09pGbI04tO9dQ.png" /></figure><p><strong>Application Details</strong></p><ul><li>Team: Mobile</li><li>Framework : KTOR <a href="https://ktor.io/">https://ktor.io/</a> because Mobile Dev Team familiar with Kotlin</li><li>Type: API Mapping</li><li>Resource:</li></ul><pre>1 pod<br>limits:<br>  cpu: &#39;4&#39;<br>  memory: 4Gi<br>requests:<br>  cpu: 100m<br>  memory: 100Mi</pre><ul><li>Platform: Openshift4</li></ul><h3><strong>Garbage collection log</strong></h3><ul><li>I have fork develop team application repo to my custom repo</li><li>Let see Dockerfile</li></ul><pre># Stage 1: Building the application<br>FROM gradle:8.4.0-jdk17 AS build<br>COPY --chown=gradle:gradle . /home/gradle/src<br>WORKDIR /home/gradle/src<br>RUN gradle buildFatJar --no-daemon<br><br># Stage 2: Running the application<br>FROM openjdk:17<br>EXPOSE 8080:8080<br>RUN mkdir /app<br>COPY --from=build /home/gradle/src/app/build/libs/*.jar /app/app-test.jar<br><br>ENTRYPOINT [&quot;java&quot;, &quot;-Xms512m&quot;, &quot;-Xmx1g&quot;, &quot;-XX:+UseG1GC&quot;, &quot;-jar&quot;, &quot;app/app-test.jar&quot;]</pre><ul><li>Change ENTRYPOINT</li></ul><pre>ENTRYPOINT [&quot;java&quot;, &quot;-Xms512m&quot;, &quot;-Xmx1g&quot;, &quot;-XX:+UseG1GC&quot;, &quot;-Xlog:gc*:file=/var/log/gc.log:time,tags:filecount=5,filesize=10m&quot;, &quot;-jar&quot;, &quot;app/app-test.jar&quot;]</pre><ul><li>Deploy to kubernetes and exec to pod</li></ul><pre>kubectl exec -it pod/app-test -n jiw-test /bin/bash<br><br>cat /var/log/gc.log</pre><p>In case of Openshift4 I can see log in UI Terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hStbV4N0FL84b9pZn8KSHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdDclre-qy5_1ApZ-4CIIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ay0T3YjuKzgt9adoYAHaHg.png" /></figure><ul><li>Start Load test and see log again.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14hqfjrVVyYb5lej9_DnWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8OkmAg6LsHaFLVJc82zCg.png" /></figure><ul><li>In Line</li></ul><p>Pause Young (Normal) (G1 Evacuation Pause) 315M-&gt;19M(512M) 13.237ms</p><p><strong>“It mean GC is working fine.”</strong></p><h3>Cloud Profiler</h3><ul><li>Install Google Cloud Profiler and enable heap memory in Dockerfile</li></ul><pre># Stage 1: Building the application<br>FROM gradle:8.4.0-jdk17 AS build<br>COPY --chown=gradle:gradle . /home/gradle/src<br>WORKDIR /home/gradle/src<br>RUN gradle buildFatJar --no-daemon<br><br># Stage 2: Running the application<br>FROM openjdk:17<br>EXPOSE 8080:8080<br><br># Install wget<br>RUN microdnf update \<br> &amp;&amp; microdnf install --nodocs wget unzip \<br> &amp;&amp; microdnf clean all \<br> &amp;&amp; rm -rf /var/cache/yum<br><br># Get google cloud profiler<br>RUN mkdir -p /opt/cprof &amp;&amp; \<br>   wget -q -O- https://storage.googleapis.com/cloud-profiler/java/latest/profiler_java_agent.tar.gz \<br>   | tar xzv -C /opt/cprof<br><br>RUN ls /opt/cprof<br><br>RUN mkdir /app<br>COPY --from=build /home/gradle/src/app/build/libs/*.jar /app/app-test.jar<br><br>ENTRYPOINT [&quot;java&quot;, &quot;-agentpath:/opt/cprof/profiler_java_agent.so=-cprof_service=app-test,-cprof_service_version=0.0.1,-cprof_project_id=gcp-devops,-cprof_enable_heap_sampling=true&quot;, &quot;-Xms512m&quot;, &quot;-Xmx1g&quot;, &quot;-XX:+UseG1GC&quot;, &quot;-Xlog:gc*:file=/var/log/gc.log:time,tags:filecount=5,filesize=10m&quot;, &quot;-jar&quot;, &quot;app/app-test.jar&quot;]</pre><ul><li>Create ConfigMap</li></ul><pre>apiVersion: v1<br>data:<br>  GOOGLE_APPLICATION_CREDENTIALS: /key/app-test.json<br>kind: ConfigMap<br>metadata:<br>  labels:<br>    app: app-test<br>  name: app-test-env<br>  namespace: jiw-test</pre><ul><li>Change Deployment for ConfigMapRef</li></ul><pre>spec:<br>  containers:<br>  - envFrom:<br>    - configMapRef:<br>        name: app-test-env</pre><ul><li>Create secret for json key that have access right for Profiler.</li></ul><pre>apiVersion: v1         <br>kind: Secret    <br>type: Opaque<br>metadata:                 <br>  name: app-test-secret<br>  namespace: jiw-test<br>stringData:  <br>  app-test.json: |<br>    {<br>      &lt;REPLACE JSON KEY&gt;<br>    }</pre><ul><li>Create VolumeMounts</li></ul><pre>spec:<br>  containers:<br>  - envFrom:<br>    - configMapRef:<br>        name: api-test-env<br>    image: &lt;IMAGES&gt;<br>    imagePullPolicy: Always<br>    livenessProbe:<br>      failureThreshold: 3<br>      periodSeconds: 3<br>      successThreshold: 1<br>      tcpSocket:<br>        port: 8080<br>      timeoutSeconds: 1<br>    name: app-test<br>    ports:<br>    - containerPort: 8080<br>      protocol: TCP<br>    readinessProbe:<br>      failureThreshold: 3<br>      initialDelaySeconds: 5<br>      periodSeconds: 3<br>      successThreshold: 1<br>      tcpSocket:<br>        port: 8080<br>      timeoutSeconds: 5<br>    resources:<br>      limits:<br>        cpu: 4000m<br>        memory: 4096Mi<br>      requests:<br>        cpu: 200m<br>        memory: 200Mi<br>    volumeMounts:<br>    - mountPath: /key<br>      name: app-test-secret-volume<br>      readOnly: true<br>  volumes:<br>  - name: app-test-secret-volume<br>    secret:<br>      secretName: app-test-dev</pre><ul><li>Build and Deploy</li><li>Go to google cloud and search for Profiler</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*yGSSERGUFf7rYYBNP7JWng.png" /></figure><ul><li>Select Profile type: Heap</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*CxNCVs_XVuNi46nBLZE9IA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVVgCutNXVAbsdWQXJerZw.png" /></figure><ul><li>Select Function</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*orWcHWcsd7JU-bnKzsUArw.png" /></figure><ul><li>Click on Total to sort Total used and Count</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*DdStKP6CoZ4cjz6v4ra9Ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Y1slNpB3M5kP4ZROV-_P3w.png" /></figure><p><strong>“It mean No single function consume high memory”</strong></p><h3><strong>Api to run GC</strong></h3><ul><li>I have test API</li></ul><pre>get(&quot;/clearGC&quot;) {<br>    System.gc()<br>    call.respondText { &quot;Clear cg.&quot; }<br>}</pre><ul><li>After curl /clearGC then memory can reduce from 1.61GB-&gt;1.39GB.</li><li><strong>“So It mean nothing.”</strong></li></ul><h3><strong>Dump Memory</strong></h3><ul><li>Restart pod to clear everything now my pod use memory about 500MB</li><li>Exec in to pod</li></ul><pre>kubectl exec -it pod/app-test -n jiw-test /bin/bash</pre><ul><li>Run jps to show the status of available JVMs on a machine.So you will get ID of app-test.jar that running on</li></ul><pre>jps</pre><ul><li>Dump memory</li></ul><pre>jcmd 1 GC.heap_dump dump-500.hprof</pre><ul><li>Copy from Cluster to my local machine</li></ul><pre>kubectl cp jiw-test/app-test-7f988f94cc-pwvm4:dump-500.hprof app-test-dump/dump-500.hprof</pre><ul><li>Run Load Test</li><li>Dump memory again when finish load test Now pod consume memory 1.5GB</li></ul><pre>jcmd 1 GC.heap_dump dump-1500.hprof</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*Wn7drU5pzJT9C0cMjEWLdA.png" /></figure><ul><li>Copy from Cluster to my local machine</li></ul><pre>kubectl cp jiw-test/app-test-7f988f94cc-pwvm4:dump-1500.hprof app-test-dump/dump-1500.hprof</pre><ul><li>Install VisualVM(Mac)</li></ul><pre>brew update<br><br>brew install visualvm</pre><ul><li>Install VisulVM(Ubuntu)</li></ul><pre>sudo apt update<br>sudo apt install visualvm</pre><ul><li>Open VisualVM on terminal or GUI</li></ul><pre>visualvm</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*l5cGmTmmJD5IVPGDrAl2sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxESzBqanSSRtA2N4y4MqQ.png" /></figure><ul><li>Open Dumpfile for 1500 MB</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sP6Fqh5Ca3iPI5V7_rY1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S68PriMvM8IfM4lxXQU-6g.png" /></figure><ul><li>Change from Summary to Object</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*f4Drh5YdmdnZ30rQPhr2vA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYAgX1EH3WJXOUfZgpHpSg.png" /></figure><ul><li>Click compare and select dump-500</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*pOHvlshiG09UFIY6pSvS-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*JBYfcM2LkfFIxresI5c18w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSB8_f_ew4LrLNW7uE8C8Q.png" /></figure><p><strong>“After compare Dump memory when 1.5GB and 500MB memory Count object increase by only data type and class in Java”</strong></p><h3><strong>Hello world KTOR vs Nodejs</strong></h3><p>Finally!!!! I decide to investigate KTOR (<a href="https://ktor.io/">https://ktor.io/</a>.) Hello world</p><ul><li>Start pod at 500 MB (include istio sidecar)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMGWK3F0NHRhEpUxxQYe9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*Lg7woiRmWIWunpp85T8AQg.png" /></figure><ul><li>Load test 100 vuser with 10K count</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*fddiewC64ZQtx7phg4jt1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gRdOgpOSTt3nh7pbSL_VZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Amc3PlPo4uyByMv7NdT6wA.png" /></figure><ul><li>Memory from 500MB to 1GB (500MB)</li></ul><p>I have Test simple rest api with Express Node.js</p><ul><li>Start pod at 400 MB (include istio sidecar)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFF175xSUeBydLRmFu3f0w.png" /></figure><ul><li>Load test 100 vuser with 10K count same as KTOR</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9xBbwcm_nlZ2M_LaxJEnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-Nu1tPqcKbJTdd1U9hyzA.png" /></figure><ul><li>Memory from 400MB to 600MB (200MB)</li></ul><h3>Summary</h3><p>After I have result</p><ul><li>Garbage collection log</li><li>Cloud Profiler</li><li>Api to run GC</li><li>Dump Memory</li><li>Hello world KTOR vs Nodejs</li></ul><p>I have summary result and discuss to Developer Team. Before investigation I think it because some class or lib from developer be root cause. But when investigation finished It consume high memory from KTOR itself.</p><p>Form my opinion if this application serve load normally then it can go live. But because this application is Mapping API that serve high transaction of mobile application this case will be new critical service.</p><p>Finally we design to go on POC this application without go live on production. Test feature that importance for mobile. If this feature can solve problem and improve user experience for customer. This feature may handled by backend team that have more experience with backend application.</p><p>!!! Have fun !!!</p><p>I hope this topic may make some idea to someone</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e68809f1dbbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform provision multiple vm with multiple network interface and patch update from AWX (ansible)]]></title>
            <link>https://dounpct.medium.com/terraform-provision-multiple-vm-with-multiple-network-interface-and-patch-update-from-awx-ansible-82bda5100cfd?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/82bda5100cfd</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 17:30:12 GMT</pubDate>
            <atom:updated>2024-03-09T17:37:44.839Z</atom:updated>
            <content:encoded><![CDATA[<p>In our Devops team, Service request for provisioning VM on premises that we used vsphere have so much.</p><p>In the past we create vm by cloning from golden image template or vm that we already patch update and hardening.</p><p>For example a service request from DBA Team</p><pre>Please provision VM servers on Production for .... team<br><br>Hostname : D2P-MongoDBD01-03<br>Server Role: Mongodb replica cluster<br>Number of server: 3<br>H/W Spec<br>OS : Oracle Linux 8<br>CPU: 8 cores<br>Memory: 24 GB<br>swap disk : 8GB<br>Disk Data sizing: /data  300 GB   (type xfs, separate SCSI controller)</pre><ul><li>DevOps Manager assign SR to Devops engineer that take care with those team</li><li>DevOps engineer need to check with empty ip in range of that team and fill back to SR.</li></ul><pre>Please provision VM servers on Production for .... team<br><br>Hostname : D2P-MongoDBD01-03<br>Server Role: Mongodb replica cluster<br>Number of server: 3<br>H/W Spec<br>OS : Oracle Linux 8<br>CPU: 8 cores<br>Memory: 24 GB<br>swap disk : 8GB<br>Disk Data sizing: /data  300 GB   (type xfs, separate SCSI controller)<br><br>Hostname/IP address<br><br>D2P-MongoDBB01 X.X.X.X<br>D2P-MongoDBB02 X.X.X.X<br>D2P-MongoDBB03 X.X.X.X</pre><ul><li>We login Vcenter and try to find closest resource with SR for checking with how interface should be etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*mM1aLxuR2me0ODJD2ulmbw.png" /></figure><ul><li>We start to clone from VM that up to date with security hardening.</li><li>After we clone vm and done then we login with web console then change ip, host name, start network.</li><li>We ssh with ssh client to vm and install some tools that need to install from SR then we finish first VM.</li><li>We clone another 2 vm from first VM and change IP Hostname and so on.</li><li>We install some tool in 3 vm again with tools that need to install after have new hostname. because each host name will register and have cost count by hostname.</li></ul><p>If you can see we need to do a lot step. some team will have more and some team will have less. New DevOps will have struggle for create VM and need to ask college for standard of team. Another one thing we have many DevOps so a lot of standard.</p><p>So I have project to create vm automation for following concept</p><ul><li>Easiest</li><li>Reduce time</li><li>Standard.</li></ul><p>So in this project have tools</p><ul><li>Terraform</li><li>Jenkins pipeline</li><li>AWX (Ansible)</li></ul><p><strong>Terraform</strong></p><p>Terraform is an open-source Infrastructure as Code (IaC) software tool created by HashiCorp. I will use Terraform for provision VM from Vsphere Vmware.</p><ul><li>Please download and install Terrafrom first <a href="https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli">https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli</a></li><li>Create main.tf this is main or core file for terraform what to do.</li></ul><pre>provider &quot;vsphere&quot; {<br>  user                 = var.vsphere_user<br>  password             = var.vsphere_password<br>  vsphere_server       = var.vsphere_server<br>  allow_unverified_ssl = true<br>}<br><br>data &quot;vsphere_datacenter&quot; &quot;datacenter&quot; {<br>  name = var.vsphere_datacenter<br>}<br><br>data &quot;vsphere_datastore&quot; &quot;datastore&quot; {<br>  count = var.vsphere_datastore != null ? 1 : 0<br>  name = var.vsphere_datastore<br>  datacenter_id = data.vsphere_datacenter.datacenter.id<br>}<br>data &quot;vsphere_datastore_cluster&quot; &quot;datastore_cluster&quot; {<br>  count = var.vsphere_datastore_cluster != null ? 1 : 0<br>  name          = var.vsphere_datastore_cluster<br>  datacenter_id = data.vsphere_datacenter.datacenter.id<br>}<br>data &quot;vsphere_compute_cluster&quot; &quot;cluster&quot; {<br>  name = var.vsphere_cluster<br>  datacenter_id = data.vsphere_datacenter.datacenter.id<br>}<br><br>data &quot;vsphere_resource_pool&quot; &quot;pool&quot; {<br>  name = var.vsphere_pool<br>  datacenter_id = data.vsphere_datacenter.datacenter.id<br>}<br><br>data &quot;vsphere_network&quot; &quot;network&quot; {<br>  count         = length(var.vsphere_network)<br>  name          = var.vsphere_network[count.index]<br>  datacenter_id = data.vsphere_datacenter.datacenter.id<br>}<br><br>data &quot;vsphere_virtual_machine&quot; &quot;template&quot; {<br>  name = var.virtual_template<br>  datacenter_id = data.vsphere_datacenter.datacenter.id<br>}<br><br>resource &quot;vsphere_virtual_machine&quot; &quot;vm&quot; {<br>  for_each = var.virtual_machines<br><br>  name             = each.key<br>  resource_pool_id = data.vsphere_resource_pool.pool.id<br>  datastore_cluster_id = length(data.vsphere_datastore_cluster.datastore_cluster) == 1 ? data.vsphere_datastore_cluster.datastore_cluster[0].id : null   <br>  datastore_id     = length(data.vsphere_datastore.datastore) == 1 ? data.vsphere_datastore.datastore[0].id : null<br><br>  num_cpus         = var.vm_cpu<br>  memory           = var.vm_memory<br>  guest_id         = data.vsphere_virtual_machine.template.guest_id<br>  scsi_type        = data.vsphere_virtual_machine.template.scsi_type<br>  firmware         = data.vsphere_virtual_machine.template.firmware<br><br>  scsi_controller_count  = var.scsi_controller_count != &quot;&quot; ? var.scsi_controller_count : &quot;1&quot;<br><br>  cpu_hot_add_enabled = true<br>  memory_hot_add_enabled = true<br><br>  wait_for_guest_net_timeout = 0<br>  wait_for_guest_ip_timeout  = 0<br><br>  dynamic &quot;network_interface&quot; {<br>    for_each = data.vsphere_network.network<br>    content {<br>      network_id   = network_interface.value.id<br>      adapter_type = data.vsphere_virtual_machine.template.network_interface_types[0]<br>    }<br>  }<br>  <br>  clone {<br>    template_uuid = data.vsphere_virtual_machine.template.id<br>    customize {<br>      linux_options {<br>        host_name = each.key<br>        domain    = var.host_domain<br>      }<br><br>      dynamic &quot;network_interface&quot; {<br>        for_each = [for i in range(length(var.virtual_machines[each.key][&quot;ip&quot;])) : { <br>          ip: var.virtual_machines[each.key][&quot;ip&quot;][i], <br>          netmask: var.virtual_machines[each.key][&quot;netmask&quot;][i]<br>        }]<br><br>        content {<br>          ipv4_address = network_interface.value.ip<br>          ipv4_netmask = network_interface.value.netmask<br>        }<br>      }<br>      <br>      ipv4_gateway = var.network_gateway<br>      dns_server_list = var.dns_server_list<br>    }<br>  }<br>  <br>  disk {<br>    label            = &quot;disk0&quot;<br>    size             = data.vsphere_virtual_machine.template.disks.0.size<br>    thin_provisioned = data.vsphere_virtual_machine.template.disks.0.thin_provisioned<br>  }<br>  <br>  dynamic &quot;disk&quot; {<br>    for_each = var.extra_disk_list<br>    content {<br>      label            = disk.key<br>      size             = disk.value.size<br>      thin_provisioned = data.vsphere_virtual_machine.template.disks.0.thin_provisioned    <br>      unit_number      = disk.value.unit_number<br>    }<br>  }<br>}</pre><p>In above I use for_each for loop vm and use dynamic for loop multiple interface and multiple disk</p><ul><li>Create variables.tf</li></ul><pre><br>variable &quot;vsphere_server&quot; {<br>  description = &quot;vCenter server FQDN or IP - Example: vcsa01-z67.sddc.lab&quot;<br>}<br><br>variable &quot;vsphere_user&quot; {<br>  description = &quot;vSphere username to use to connect to the environment - Default: administrator@vsphere.local&quot;<br>}<br><br>variable &quot;vsphere_password&quot; {<br>  description = &quot;vSphere password&quot;<br>}<br><br>variable &quot;vsphere_datacenter&quot; {<br>  description = &quot;vSphere datacenter&quot;<br>}<br>variable &quot;vsphere_datastore&quot; {<br>  description = &quot;vSphere datastore&quot;<br>}<br>variable &quot;vsphere_datastore_cluster&quot; {<br>  description = &quot;vSphere datastore cluster&quot;<br>}<br>variable &quot;vsphere_cluster&quot; {<br>  description = &quot;vSphere cluster&quot;<br>}<br>variable &quot;vsphere_pool&quot; {<br>  description = &quot;vSphere pool&quot;<br>}<br><br>variable &quot;dns_server_list&quot; {<br>  type    = list<br>}<br><br>variable &quot;virtual_template&quot; {<br>  description = &quot;virtual template&quot;<br>}<br><br>variable &quot;virtual_machines&quot; {<br>  type = map(object({<br>    ip = list(string),<br>    netmask = list(string),<br>  }))<br>}<br><br>variable &quot;vm_cpu&quot; {<br>  description = &quot;vm cpu&quot;<br>}<br>variable &quot;vm_memory&quot; {<br>  description = &quot;vm memory&quot;<br>}<br>variable &quot;network_gateway&quot; {<br>  description = &quot;network gateway&quot;<br>}<br>variable &quot;host_domain&quot; {<br>  description = &quot;host domain&quot;<br>}<br>variable &quot;vm_user&quot; {<br>  description = &quot;vm user for run script&quot;<br>}<br>variable &quot;vm_password&quot; {<br>  description = &quot;vm password for run script&quot;<br>}<br><br>variable &quot;scsi_controller_count&quot; {<br>  description = &quot;vm pscsi_controller_count&quot;<br>}<br><br>variable &quot;extra_disk_list&quot; {<br>  type = map(object({<br>    size = string<br>    unit_number = string<br>  }))<br>}<br><br>variable &quot;vsphere_network&quot; {<br>  description = &quot;List of network names&quot;<br>  type        = list(string)<br>  default     = [&quot;NETWORK_1&quot;, &quot;NETWORK_2&quot;]<br>}</pre><ul><li>Create terraform.tfvars for parameter that we will create VM</li></ul><pre>vsphere_server      = &quot;X.X.X.X&quot;<br>vsphere_user        = &quot;robot@vsphere.local&quot;<br><br>vsphere_datacenter  = &quot;DC01&quot;<br><br>vsphere_datastore   = &quot;DS99_D2D_APP&quot;<br>vsphere_datastore_cluster = null<br><br>vsphere_cluster     = &quot;TTT-NON-PROD&quot;<br>vsphere_pool        = &quot;AUTOMATION&quot;<br><br>virtual_template    = &quot;GoldenImageOracle8.5&quot;<br>vm_cpu              = &quot;4&quot;<br>vm_memory           =  &quot;8192&quot;<br>network_gateway     = &quot;X.X.X.X&quot;<br>host_domain         = &quot;&quot;<br>vm_user         = &quot;root&quot;<br>dns_server_list = [&quot;X.X.X.X&quot;,&quot;X.X.X.X&quot;]<br><br>vsphere_network = [&quot;TTT_SERVICE_01&quot;,&quot;TTT_MANAGE_01&quot;]<br>virtual_machines = {<br>    VM-AUTOMATION-01 = {<br>      ip = [&quot;1X.X.X.X&quot;,&quot;X.X.X.X&quot;],<br>      netmask = [&quot;24&quot;,&quot;24&quot;]<br>    },<br>  }<br><br>extra_disk_list = {<br>  disk1 = {<br>      size = &quot;8&quot;,<br>      unit_number = &quot;1&quot;,<br>  },<br>  disk2 = {<br>      size = &quot;16&quot;,<br>      unit_number = &quot;2&quot;,<br>  },<br>  disk3 = {<br>      size = &quot;50&quot;<br>      unit_number = &quot;3&quot;<br>  },<br>}</pre><ul><li>In code above we have 1 vm with 2 interface network and extra 4 disk</li><li>For multiple vm</li></ul><pre>virtual_machines = {<br>    VM-AUTOMATION-01 = {<br>      ip = [&quot;X.X.X.X&quot;,&quot;X.X.X.X&quot;],<br>      netmask = [&quot;24&quot;,&quot;24&quot;]<br>    },<br>    VM-AUTOMATION-02 = {<br>      ip = [&quot;X.X.X.X&quot;,&quot;X.X.X.X&quot;],<br>      netmask = [&quot;24&quot;,&quot;24&quot;]<br>    },<br>  }</pre><ul><li>For vsphere_datastore and vsphere_datastore_cluster we need to select only one. If we use datastore then another one set null. On the other hand if we use datastore cluster then set another one to null.</li><li>Run Terraform</li></ul><pre>terraform init<br><br>vsphere_password=&lt;vsphere_password&gt;<br>vm_password=&lt;vm_password&gt;<br><br>terraform plan -var=vsphere_password=${vsphere_password} -var=vm_password=${vm_password}<br>terraform apply -var=vsphere_password=${vsphere_password} -var=vm_password=${vm_password}</pre><ul><li>Code here : <a href="https://github.com/dounpct/terraform-vmware-vsphere/tree/master">https://github.com/dounpct/terraform-vmware-vsphere/tree/master</a></li><li>This Terraform can only provisioning vm without running startup script.</li><li>You can wrote more startup script with provisioner “remote-exec” as you wish. But I don’t use.!!! Because I prefer to use Ansible.</li></ul><p><strong>AWX</strong></p><p>AWX, it’s an open-source community project sponsored by Red Hat. AWX provides a web-based user interface, REST API, and task engine built on top of Ansible which is an IT automation tool.</p><p>For me I use AWX by import Ansible playbook then request for action via rest api such as curl command.</p><p><strong>Install AWX</strong></p><ul><li>Refer to new version of AWX now. they pefer to install in kubernetes system. Sure I use ArgoCD to install.</li><li>Note:<a href="https://github.com/ansible/awx/blob/devel/INSTALL.md">https://github.com/ansible/awx/blob/devel/INSTALL.md</a></li><li>This is about Helm in ArgoCD</li></ul><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: awx-operator<br>spec:<br>  project: default<br>  source:<br>    path: &#39;awx-operator&#39;<br>    repoURL: &#39;https://github.com/dounpct/argocd-deployment.git&#39;<br>    targetRevision: master<br>    plugin:<br>      env:<br>        - name:  INIT_ARGS<br>          value: &quot;helm dep update&quot;<br>        - name:  ARG_PARAMETERS<br>          value: &quot;helm template awx-operator -n awx-operator . -f values/values.yaml &quot;<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: awx-operator<br>  syncPolicy:<br>    syncOptions:<br>      - CreateNamespace=true</pre><ul><li>Create folder awx-operator</li><li>Create Chart.yaml</li></ul><pre>apiVersion: v2<br>name: helm-awx-operator<br>description: A Helm chart for Kubernetes<br><br># A chart can be either an &#39;application&#39; or a &#39;library&#39; chart.<br>#<br># Application charts are a collection of templates that can be packaged into versioned archives<br># to be deployed.<br>#<br># Library charts provide useful utilities or functions for the chart developer. They&#39;re included as<br># a dependency of application charts to inject those utilities and functions into the rendering<br># pipeline. Library charts do not define any templates and therefore cannot be deployed.<br>type: application<br><br># This is the chart version. This version number should be incremented each time you make changes<br># to the chart and its templates, including the app version.<br># Versions are expected to follow Semantic Versioning (https://semver.org/)<br>version: 1.0.1<br><br># This is the version number of the application being deployed. This version number should be<br># incremented each time you make changes to the application. Versions are not expected to<br># follow Semantic Versioning. They should reflect the version the application is using.<br>appVersion: 1.16.0<br>dependencies:<br>  - name: awx-operator<br>    version: 2.5.1<br>    repository: https://ansible.github.io/awx-operator/<br>    alias: operator</pre><ul><li>Create templates/secret.yaml</li></ul><pre>apiVersion: v1<br>kind: Secret<br>type: Opaque<br>metadata:<br>  name: {{ .Values.operator.AWX.name }}-admin-password<br>data:<br>  password: &lt;path:projects/362159383816/secrets/awx-admin-password#awx-admin-password | base64encode&gt;</pre><ul><li>Create values/values.yaml</li></ul><pre>operator:<br>  AWX:<br>    enabled: true<br>    name: ansible-awx<br>    spec:<br>      service_type: LoadBalancer<br>      admin_password_secret: awx-custom-admin-password</pre><ul><li>Refer values: <a href="https://github.com/ansible/awx-operator/blob/devel/.helm/starter/values.yaml">https://github.com/ansible/awx-operator/blob/devel/.helm/starter/values.yaml</a></li><li>Use Argocd to syn with awx-operator application</li><li>If you need to install with helm install</li></ul><pre>helm repo add awx-operator https://ansible.github.io/awx-operator/<br>helm install my-awx-operator awx-operator/awx-operator -n awx --create-namespace -f my-values.yml --version 1.3.0</pre><ul><li>Login AWX</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5a68iKFSyQ1jFSA4NFzwA.png" /></figure><ul><li>In our VM I have many playbook for patch after create VM with Terraform such as extend-swap, extend-data, update route file and so on.</li><li>This is example of extend-swap.yaml</li></ul><pre>- name: Extend Swap<br>  hosts: all<br>  vars:<br>    swap_extend: &quot;1&quot;<br>    ssh_options: -o PreferredAuthentications=password -o PubkeyAuthentication=no -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null<br>    ansible_ssh_common_args: -o ProxyCommand=&quot;sshpass -p &#39;{{ ansible_ssh_pass }}&#39; ssh -W %h:%p -q sysen@{{ bastion_ip }} {{ ssh_options }}&quot;<br>  tasks:<br>    - name: Show Swap Before Change<br>      shell: &quot;free -m&quot;<br>      register: command_output<br>    - debug:<br>        var: command_output.stdout_lines<br>    <br>    - name: Check current swap spaces<br>      command: swapon --show<br>      register: swapon_result<br><br>    - name: Turn off swap<br>      command: swapoff -v /dev/vg00/swap<br>      when: &quot;&#39;/dev/dm-1&#39; in swapon_result.stdout&quot;<br>    <br>    - name: Extend LV<br>      shell: |<br>        lvextend -L +{{ swap_extend }}G /dev/vg00/swap<br>      ignore_errors: true      <br>      register: command_output<br>    - debug:<br>        var: command_output.stdout_lines<br>    <br>    - name: MK SWAP<br>      shell: |<br>        mkswap /dev/vg00/swap<br>      register: command_output<br>    - debug:<br>        var: command_output.stdout_lines<br><br>    - name: SWAP ON<br>      shell: |<br>        swapon -v /dev/vg00/swap        <br>      register: command_output<br>    - debug:<br>        var: command_output.stdout_lines<br>    <br>    - name: Show Swap Before Change<br>      shell: &quot;free -m&quot;<br>      register: command_output<br>    - debug:<br>        var: command_output.stdout_lines<br></pre><ul><li>Create all your playbook to git repo.</li><li>Create Project and refer to git repo.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjc-EP7UqC1NZSX6Cfe4PA.png" /></figure><ul><li>Create Templates</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23Y1KcY7gbVJg6Wm90Licg.png" /></figure><ul><li>Then you can lunch template now and specific inventory with host. More over if you see at url then you can see template ID.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*JNusmc0v2NMt6Jv1f3guGQ.png" /></figure><p>How to trigger template with curl command</p><ul><li>Create inventory</li></ul><pre>curl -X POST --user admin:$password &quot;http:/&lt;AWX_SERVER&gt;/api/v2/inventories/&quot; \<br>    -H &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>            &quot;name&quot;: &quot;inventory-atm-00001&quot;,<br>            &quot;organization&quot;: 1<br>        }&#39; \<br>        | jq .id</pre><ul><li>So you will get inventory ID then use it for create host</li></ul><pre>curl -X POST --user admin:$password &quot;http://&lt;AWX_SERVER&gt;/api/v2/inventories/HOST_ID/hosts/&quot; \<br>    -H &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>            &quot;name&quot;: &quot;X.X.X.X&quot;,<br>            &quot;description&quot;: &quot;host-atm&quot;<br>        }&#39; \<br>        | jq</pre><ul><li>Run Template</li></ul><pre>curl -X POST --user admin:$password &quot;http://&lt;AWX_SERVER&gt;/api/v2/job_templates/41/launch/&quot; \<br>    -H &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>            &quot;inventory&quot;:&quot;84&quot;,<br>            &quot;extra_vars&quot;: <br>            {<br>                &quot;bastion_ip&quot;:&quot;X.X.X.X&quot;,<br>                &quot;swap_extend&quot;:&quot;8&quot;<br>            }<br>        }&#39; \<br>        | jq .</pre><ul><li>Finally if you develop template that will can rerun every status it will be great!!!!</li></ul><p><strong>Jenkins Pipeline</strong></p><p>I use Jenkins pipeline to complete all vm automation project</p><ul><li>Have user interface.</li><li>Get IP from VCenter.</li><li>Limit range ip from pipeline.</li><li>Check IP from VM Center that in used or not.</li><li>Run Terraform with pass parameter.</li><li>Run AWX.</li><li>etc.</li></ul><p>User Interface</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKhX9A4y9zGIvrzsEb1K-A.png" /></figure><p>Check IP with VCenter: getVmIP.ps1</p><pre>$vcenter=$args[0]<br>$user=$args[1]<br>$password=$args[2]<br>$filter_subnet=$args[3]<br>$std_out_file=$args[4]<br><br>Set-PowerCLIConfiguration -ProxyPolicy NoProxy -Scope Session -confirm:$false<br>Set-PowerCLIConfiguration -ParticipateInCeip $false -confirm:$false<br>Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -confirm:$false<br><br>Connect-VIServer -Server $vcenter -Protocol https -User $user -Password $password<br><br>Get-VM | Select @{N=&quot;IP-ADDR&quot;;E={@($_.guest.IPAddress -like &quot;${filter_subnet}&quot; -join &quot;|&quot;)}} | grep ${filter_subnet} &gt; $std_out_file</pre><p>Jenkinsfile</p><pre>@Library(&#39;pipeline-libraries@master&#39;) _<br><br>pipeline<br>{<br>    agent<br>    {<br>        node <br>        {<br>            label &quot;master&quot;<br>        }<br>    }<br><br>    stages<br>    {<br>        stage(&#39;Generate IP&#39;) <br>        { <br>            steps<br>            {<br>                script <br>                {                    <br>                    println(&quot;Get VM IP&quot;)<br>                    artifactVmIP()                                   <br>                }<br>            }<br>        }  <br><br>        stage(&#39;Provision VM&#39;) <br>        { <br>            steps<br>            {<br>                script <br>                {<br>                    println(&quot;Terraform Apply VM&quot;)<br>                    artifactVmProvisioning()                                        <br>                }<br>            }<br>        }<br>        <br>        stage(&#39;Configuration VM&#39;) <br>        { <br>            steps<br>            {<br>                script <br>                {<br>                    println(&quot;Patch AWX&quot;)<br>                    artifactVmAWX()                        <br>                }<br>            }<br>        }<br>    }      <br>}</pre><ul><li>In Jenkins pipeline-libraries I create function for artifactVmIP artifactVmProvisioning and artifactVmAWX</li><li>I have yaml file for specification for each VM and Group such single interface</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*7McXDyJKkoc7uEmOWibgiw.png" /></figure><ul><li>Multiple interface</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*TTYVjO4wLreRwYWst8apdw.png" /></figure><ul><li>Group configuration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6EqukGEGfq4wWaDraOXaw.png" /></figure><blockquote>In jenkins pipeline in step artifactVmProvisioning. I create terraform with only one disk and wait for success then upgrade terraform again with second disk and next respectively. because if I create all of three disk at the same time or even create vm with complete 3 disk and clone. there may be race condition to swap between sdb and sdc that will not good.</blockquote><p><strong>Summary</strong></p><p>After my VM automation project lunch.</p><ul><li>Limit IP range from each IDC and Group have set from DevOps Manager.</li><li>DevOps manager or non experience for anyone in DevOps team can run pipeline for create VM easy. But now DevOps manager create by himself.</li><li>Time to create reduce so much.</li><li>Every VM be same standard.</li></ul><p>I hope this topic may make some idea to someone</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82bda5100cfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mlflow with Helm and serve Train Model on kubernetes]]></title>
            <link>https://dounpct.medium.com/mlflow-with-helm-and-serve-train-model-on-kubernetes-422c9228eb20?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/422c9228eb20</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 10:15:28 GMT</pubDate>
            <atom:updated>2024-02-03T10:19:41.520Z</atom:updated>
            <content:encoded><![CDATA[<p>End to End Diagram and Architecture</p><p>After I have done for implementation ML Project about Training and Serving Model to predict threat from data firewall and login logs. I would like to share further my experience for end to end that I used in this project.</p><p><strong>Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQik5FsaZTXo7_UNAB6mIA.png" /></figure><p><strong>Project</strong></p><ul><li>Predict threat from destination country and port of firewall logs</li><li>Predict threat from login time of access logs</li><li>Can handle a lot of traffic.</li></ul><p>For model training we have test about Supervised Logical reqression and UnSupervised. Supervised need target that mask as threat but from raw log.it not easy to mask as threat by human. So we design to use UnSupervised for Anomaly Detection with “LocalOutlierFactor” for return what record be anomaly</p><p>For a lot of traffic. Sure! I am DevOps Engineer I design to be deploy everything as Kubernetest Cluster that can scale pod to serve more traffic. moreover I love to deploy everything with most automation. I use ArgoCD Jenkins and GitHub Action.</p><p><strong>Develop Model</strong></p><p>I start develop model with Jupyter Extension for Visual Studio Code <a href="https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter">https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter</a>. it make me easy for running code only some part not for whole file python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFf0jw0ZqzLahA6_oMbSqA.png" /></figure><p>In python training model will compose of</p><ul><li>Load test json data : only 2–3 file of json raw data</li></ul><pre>if __name__ == &quot;__main__&quot;:<br>    df = pd.DataFrame()<br>    path_to_json = &#39;rawdata&#39; <br>    json_pattern = os.path.join(path_to_json,&#39;*.txt&#39;)<br>    file_list = glob.glob(json_pattern)<br>    <br>    xcount = 0<br><br>    for file in file_list:<br>        xcount = xcount + 1<br>        print(&quot;xcount: &quot;, xcount)<br>        print(file)<br>        data = pd.read_json(file, lines=True)<br>        df = pd.concat([df,data], ignore_index = True)<br>        if (xcount == mlflowTrainingFileLimit):<br>            break</pre><ul><li>Data preprocessing : convert unknow data and encoding</li></ul><pre>    np.set_printoptions(threshold=sys.maxsize)<br>    <br>    # df_categories = df[df[&quot;ads_country_dst&quot;].str.startswith((&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;0&#39;)) == False] <br>    df_categories = pd.concat([df[&quot;ads_country_dst&quot;]], axis=1, sort=False,)<br>    print(&quot;-------------- Count Record --------------&quot;)<br>    print(df_categories.shape[0])<br>    print(&quot;-------------- Count Record --------------&quot;)<br>    print(&quot;-------------- Count Destination Country --------------&quot;)<br>    print(df_categories.value_counts().to_string())<br>    print(&quot;-------------- Count Destination Country --------------&quot;)<br><br>    countryMap = mapOfCountryDst()<br>    portMap = mapOfPort()<br>    print(&quot;-------------- Number of Country in Encoding --------------&quot;)<br>    print(&quot;country_key : &quot;, len(countryMap.keys()))<br>    print(&quot;country_count : &quot;, len(set(countryMap.values())))<br>    print(&quot;-------------- Number of Country in Encoding --------------&quot;)    <br>    print(&quot;-------------- Show Country Not in list --------------&quot;)<br>    print(df_categories[~df_categories[&#39;ads_country_dst&#39;].isin(countryMap.keys())].value_counts().to_string())<br>    print(&quot;-------------- Show Country Not in list --------------&quot;)<br><br>    df_categories = df_categories.mask(~df_categories.isin(countryMap.keys()),&#39;OTHER&#39;)<br>    print(&quot;Mask OTHER done&quot;)<br>    X = df_categories.replace({&#39;ads_country_dst&#39;: countryMap})<br>    print(&quot;Frequency encoding done&quot;)<br>    print(&quot;-------------- Show X --------------&quot;)<br>    print(X)<br>    print(&quot;-------------- Show X --------------&quot;)<br>    # x_scaler = StandardScaler().fit(X)<br>    # print(&quot;Mean of x is:&quot;, x_scaler.mean_)<br>    # print(&quot;Variance of x is:&quot;, x_scaler.var_)<br>    # print(&quot;Standard deviation of x is:&quot;, x_scaler.scale_)<br>    # x_scaled = x_scaler.transform(X)<br>    # print(x_scaled)<br>    print(&quot;-------------- Port --------------&quot;)<br>    df_categories = pd.concat([df_categories,df[&quot;ads_dst_port&quot;]], axis=1, sort=False,)<br>    ads_dst_port = pd.concat([df[&quot;ads_dst_port&quot;]], axis=1, sort=False,).astype(str)<br>    ads_dst_port = ads_dst_port.mask(~ads_dst_port.isin(portMap.keys()), &#39;OTHER&#39;)<br>    ads_dst_port = ads_dst_port.replace({&#39;ads_dst_port&#39;: portMap})<br>    print(&quot;-------------- Port --------------&quot;)<br><br>    X = pd.concat([X,ads_dst_port], axis=1, sort=False,)<br>    print(&quot;-------------- Show X --------------&quot;)<br>    print(X.to_string())    <br>    print(&quot;-------------- Show X --------------&quot;)<br>    <br>    normalPoint = 30<br>    mask = (X[&#39;ads_country_dst&#39;] &lt;= normalPoint) &amp; (X[&#39;ads_dst_port&#39;] == 0)<br>    X_Test = pd.DataFrame({&#39;test&#39;: [-1] * len(df)})<br>    X_Test.loc[mask, &#39;test&#39;] = 1<br><br>    print(&quot;-------------- Show X_Test --------------&quot;)<br>    print(X_Test)<br>    print(&quot;-------------- Show X_Test --------------&quot;)</pre><ul><li>Training the model</li></ul><pre># Call and fit the Local Outlier Factor detector<br># lof_detector = LocalOutlierFactor(n_neighbors=30, contamination=0.001,novelty=True).fit(x_scaled)<br>setNNeighbors = int((df_categories.shape[0]/300))<br>print(&quot;set n_neighbors : &quot; , setNNeighbors)<br>lof_detector = LocalOutlierFactor(n_neighbors=setNNeighbors, contamination=0.1,novelty=True).fit(X.values)<br><br>print(&quot;-------------- Model Size (MB) --------------&quot;)<br>print(&quot;{:.2f}&quot;.format(sys.getsizeof(pickle.dumps(lof_detector))/(1024*1024)))<br>print(&quot;-------------- Model Size (MB) --------------&quot;)<br><br># lof_detect = lof_detector.predict(x_scaled)<br>lof_detect = lof_detector.predict(X)</pre><ul><li>Evaluating the model and Making predictions</li></ul><pre>recordDetect,countDetect = np.unique(lof_detect, return_counts=True)<br>print(&quot;--------------Count Anomaly VS Normal-------------&quot;)<br>print(recordDetect)<br>print(countDetect)<br><br>if (len(countDetect) == 1):<br>    row_to_be_added = countDetect<br>    countDetect = np.append(np.array([0]),row_to_be_added,axis=0)<br><br>print(&quot;Anomaly = &quot; , countDetect[0] , &quot;record with &quot; , (countDetect[0])*100/(countDetect[0]+countDetect[1]) ,&quot; %&quot;)<br>print(&quot;Normal  = &quot; , countDetect[1] , &quot;record with &quot; , (countDetect[1])*100/(countDetect[0]+countDetect[1]) ,&quot; %&quot;)<br>print(&quot;--------------Count Anomaly VS Normal-------------&quot;)<br><br>print(&quot;-------------- List Destination Country Port with Prediction -------------&quot;)<br># print(type(df_categories.value_counts()))<br># print(type(df_categories))<br><br>htmlItem = &quot;&quot;<br><br>for index, value in df_categories.value_counts().items():<br>    encode = countryMap[index[0]]<br><br>    portEncode = 0<br>    if (str(index[1]) in portMap):<br>        portEncode = portMap[str(index[1])]<br><br>    predictData = lof_detector.predict([[ encode , portEncode ]])<br><br>    if (portEncode &gt; 0):<br>        print(index[0]  , &quot; | code =&quot; , encode , &quot; | Port Level = &quot;, index[1] , &quot;/&quot; , str(portEncode)  , &quot; | count =&quot;  , value , &quot; | result =&quot; , dataPredictionToString(predictData[0]))<br>    <br>    htmlItem = htmlItem + &quot;&lt;tr&gt;&lt;td&gt;&quot; + index[0] + &quot;&lt;/td&gt;&lt;td class=right-aligned&gt;&quot; + str(encode) + &quot;&lt;/td&gt;&lt;td class=right-aligned&gt;&quot; + str(index[1]) + &quot;&lt;/td&gt;&lt;td class=right-aligned&gt;&quot; + str(portEncode) + &quot;&lt;/td&gt;&lt;td class=right-aligned&gt;&quot; + str(value)+ &quot;&lt;/td&gt;&lt;td&gt;&quot; + dataPredictionToString(predictData[0]) + &quot;&lt;/td&gt;&lt;tr&gt;&quot;<br>print(&quot;-------------- List Destination Country with Prediction -------------&quot;)<br></pre><ul><li>Vitualize data or report</li></ul><pre>plt.figure(figsize=(7,7))<br># plt.scatter(x_scaled[:, 0], x_scaled[:, 0], c=lof_detect, cmap=&quot;flag&quot;, alpha=0.5)<br>plt.scatter(X.to_numpy()[:, 0], X.to_numpy()[:, 1], c=lof_detect, cmap=&quot;flag&quot;, alpha=0.1)<br>plt.title(&quot;train-ads-anomaly-dest-country-port&quot;)<br>plt.savefig(&#39;images/train-ads-anomaly-dest-country-port.png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*EYqaYQJ9CQGizVoZum3cmg.png" /></figure><pre>print(&quot;-------------- Machine Learning - Confusion Matrix -------------&quot;)<br>Accuracy = metrics.accuracy_score(X_Test, lof_detect)<br>print(&quot;Accuracy : &quot; , Accuracy)<br>Precision = metrics.precision_score(X_Test, lof_detect)<br>print(&quot;Precision : &quot; , Precision)<br>Sensitivity_recall = metrics.recall_score(X_Test, lof_detect)<br>print(&quot;Sensitivity_recall : &quot; , Sensitivity_recall)<br>Specificity = metrics.recall_score(X_Test, lof_detect, pos_label=-1)<br>print(&quot;Specificity : &quot; , Specificity)<br>F1_score = metrics.f1_score(X_Test, lof_detect)<br>print(&quot;F1_score : &quot; , F1_score)<br>print(&quot;-------------- Machine Learning - Confusion Matrix -------------&quot;)</pre><pre>confusion_matrix = metrics.confusion_matrix(X_Test, lof_detect)<br>cm_display = metrics.ConfusionMatrixDisplay(confusion_matrix = confusion_matrix, display_labels = [&quot;Anomally&quot;, &quot;Normally&quot;])<br>cm_display.plot()<br>plt.savefig(&#39;images/train-ads-anomaly-dest-country-port-confusion-matrix.png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*GkCp1y3ZjWP4tk73r2T68Q.png" /></figure><ul><li>Generate Report</li></ul><pre>htmlAnomalyVSNormally = &#39;&#39;&#39;<br>&lt;table class=&quot;table table-striped&quot;&gt;<br>    &lt;th&gt;Type&lt;/th&gt;&lt;th class=right-aligned&gt;Record&lt;/th&gt;&lt;th class=right-aligned&gt;%Record&lt;/th&gt;<br>    &lt;tr&gt;&lt;td&gt;Anomaly&lt;/td&gt;&lt;td class=right-aligned&gt;&#39;&#39;&#39; + str(countDetect[0]) + &#39;&#39;&#39;&lt;/td&gt;&lt;td class=right-aligned&gt; &#39;&#39;&#39; + str((countDetect[0])*100/(countDetect[0]+countDetect[1])) + &#39;&#39;&#39;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td&gt;Normal&lt;/td&gt;&lt;td class=right-aligned&gt;&#39;&#39;&#39; + str(countDetect[1]) + &#39;&#39;&#39;&lt;/td&gt;&lt;td class=right-aligned&gt; &#39;&#39;&#39; + str((countDetect[1])*100/(countDetect[0]+countDetect[1])) + &#39;&#39;&#39;&lt;/td&gt;&lt;/tr&gt;<br>&lt;/table&gt;<br>&#39;&#39;&#39;<br><br>htmlCountryPrediction = &#39;&#39;&#39;<br>&lt;table class=&quot;table table-striped&quot;&gt;<br>    &lt;th&gt;Country&lt;/th&gt;&lt;th class=right-aligned&gt;CODE&lt;/th&gt;&lt;th class=right-aligned&gt;Port&lt;/th&gt;&lt;th class=right-aligned&gt;Malware DST Ports Level&lt;/th&gt;&lt;th class=right-aligned&gt;Amount&lt;/th&gt;&lt;th&gt;Prediction&lt;/th&gt;<br>    &#39;&#39;&#39; + htmlItem + &#39;&#39;&#39;<br>&lt;/table&gt;<br>&#39;&#39;&#39;<br><br>htmlMatrix = &#39;&#39;&#39;<br>&lt;table class=&quot;table table-striped&quot;&gt;<br>    &lt;th&gt;Type&lt;/th&gt;&lt;th&gt;Meaning&lt;/th&gt;&lt;th class=right-aligned&gt;Score&lt;/th&gt;<br>    &lt;tr&gt;&lt;td&gt;Accuracy&lt;/td&gt;&lt;td&gt;The proportion of correctly predicted cases&lt;/td&gt;&lt;td class=right-aligned&gt;&#39;&#39;&#39; + str(Accuracy) + &#39;&#39;&#39;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td&gt;Precision&lt;/td&gt;&lt;td&gt;Positive Predictive Value&lt;/td&gt;&lt;td class=right-aligned&gt;&#39;&#39;&#39; + str(Precision) + &#39;&#39;&#39;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td&gt;Sensitivity_recall&lt;/td&gt;&lt;td&gt; True Positive Rate&lt;/td&gt;&lt;td class=right-aligned&gt;&#39;&#39;&#39; + str(Sensitivity_recall) + &#39;&#39;&#39;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td&gt;Specificity&lt;/td&gt;&lt;td&gt;True Negative Rate&lt;/td&gt;&lt;td class=right-aligned&gt;&#39;&#39;&#39; + str(Specificity) + &#39;&#39;&#39;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td&gt;F1_score&lt;/td&gt;&lt;td&gt;Balances precision and recall&lt;/td&gt;&lt;td class=right-aligned&gt;&#39;&#39;&#39; + str(F1_score) + &#39;&#39;&#39;&lt;/td&gt;&lt;/tr&gt;    <br>&lt;/table&gt;<br>&#39;&#39;&#39;<br><br>summary_table = &#39;&#39;&#39;<br>&lt;p&gt;Count Record : &#39;&#39;&#39; + str(df_categories.shape[0]) + &#39;&#39;&#39;&lt;/p&gt;<br>&lt;h2&gt;Local Outlier Factor (LOF)&lt;/h2&gt;<br>&lt;p&gt;n_neighbors : &#39;&#39;&#39; + str(setNNeighbors) + &#39;&#39;&#39;&lt;/p&gt;<br>&#39;&#39;&#39; + htmlAnomalyVSNormally + &#39;&#39;&#39;<br>&#39;&#39;&#39; + htmlCountryPrediction + &#39;&#39;&#39;<br>&lt;table class=&quot;table table-striped&quot;&gt;<br>&lt;th&gt;Local Outlier Factor (LOF)&lt;/th&gt;<br>&lt;tr&gt;<br>    &lt;td&gt;&lt;img src=&quot;train-ads-anomaly-dest-country-port-port.png&quot; alt=&quot;train-ads-anomaly-dest-country-port.png&quot;&gt;&lt;/td&gt;<br>&lt;/tr&gt;<br>    &lt;/table&gt;<br>&lt;table class=&quot;table table-striped&quot;&gt;<br>&lt;th&gt;confusion-matrix&lt;/th&gt;<br>&lt;tr&gt;<br>    &lt;td&gt;&lt;img src=&quot;train-ads-anomaly-dest-country-port-confusion-matrix.png&quot; alt=&quot;confusion-matrix&quot;&gt;&lt;/td&gt;<br>&lt;/tr&gt;<br>&lt;/table&gt;<br>&#39;&#39;&#39; + htmlMatrix + &#39;&#39;&#39;<br>&#39;&#39;&#39;<br><br>html_string = mainReportHTML(&quot;train-ads-anomaly-dest-country-port&quot;,summary_table)<br>f = open(&#39;report.html&#39;,&#39;w&#39;)<br>f.write(html_string)<br>f.close()<br></pre><ul><li>Keep Model in Mlflow</li></ul><pre>%set_env MLFLOW_TRACKING_URI=http://127.0.0.1:5000<br># %set_env MLFLOW_TRACKING_URI=http://mlflow.rtarf-ml.its-software-services.com/<br>tracking_uri = os.environ[&quot;MLFLOW_TRACKING_URI&quot;]<br># export MLFLOW_TRACKING_USERNAME=user <br># export MLFLOW_TRACKING_PASSWORD=pwd<br><br>experiment = mlflow.set_experiment(experiment_name=&#39;ads-anomaly-dest-country-port&#39;)<br>experiment_id = experiment.experiment_id<br><br>reportURL = &quot;https://minio-api.rtarf-ml.its-software-services.com/ml-report/train-ads-anomaly-dest-country-port/&quot; + jenkinsBuildID + &quot;/report.html&quot;<br><br>run_description = f&quot;&quot;&quot;<br>### Note<br>**All information** * about Training * ~~ML here~~<br>Jenkins URL: [{jenkinsURL}]({jenkinsURL})<br>Report: [{reportURL}]({reportURL})<br>&quot;&quot;&quot;<br># %set_env MLFLOW_HTTP_REQUEST_TIMEOUT=4000<br>urllib3.util.retry.Retry(total=10, backoff_factor=0.1, status_forcelist=[ 500, 502, 503, 504 ])<br>mlflow.environment_variables.MLFLOW_ARTIFACT_UPLOAD_DOWNLOAD_TIMEOUT=&#39;5000&#39;<br>mlflow.environment_variables.MLFLOW_HTTP_REQUEST_TIMEOUT=&#39;5000&#39;<br><br>with mlflow.start_run(experiment_id=experiment_id,description=run_description):<br>    mlflow.set_tracking_uri(tracking_uri)<br>    <br>    print(&quot;Artifact Location: {}&quot;.format(experiment.artifact_location))<br>    print(&quot;artifact uri : &quot; + mlflow.get_artifact_uri())<br><br>    mlflow.environment_variables.MLFLOW_ARTIFACT_UPLOAD_DOWNLOAD_TIMEOUT=&quot;5000&quot;<br><br>    mlflow.doctor()<br>    mlflow.log_param(&quot;MlflowMinioFolder&quot;, mlflowMinioFolder)<br>    mlflow.log_param(&quot;country_key&quot;, len(countryMap.keys()))<br>    mlflow.log_param(&quot;country_count&quot;, len(set(countryMap.values())))<br><br>    mlflow.log_param(&quot;SampleFile&quot;, xcount)<br>    mlflow.log_param(&quot;SampleRows&quot;, X.shape[0])<br>    # mlflow.set_tag(&quot;JenkinsURL&quot;,jenkinsURL)<br><br>    mlflow.log_metric(&quot;Anomaly&quot;, str((countDetect[0])*100/(countDetect[0]+countDetect[1])))<br>    mlflow.log_metric(&quot;Normal&quot;, str((countDetect[1])*100/(countDetect[0]+countDetect[1])))<br>    mlflow.sklearn.log_model(lof_detector, &quot;model&quot;, registered_model_name=&quot;ads-anomaly-by-dest-country&quot;)<br>    print(&quot;Model saved in run %s&quot; % mlflow.active_run().info.run_uuid)<br><br><br>print(&quot;-------------- Model save success -------------&quot;)</pre><ul><li>Serve model in Local</li></ul><pre>!mlflow models serve -m mlflow-artifacts:/229825231912337594/f8757959b00442f2a2f807d4fe9000a8/artifacts/model -p 9999 --no-conda</pre><ul><li>Test Model in Local</li></ul><pre>curl -X POST -H &quot;Content-Type:application/json&quot;                     \<br>    --data &quot;{\&quot;dataframe_split\&quot;: {\&quot;data\&quot;:[                      \<br>        [0 , 0]<br> ]}}&quot;          \<br>    http://127.0.0.1:9999/invocations | jq</pre><ul><li>Sumary all section in Jupyter to python file.</li><li>All code here: <a href="https://github.com/dounpct/soc-ml-api-localoutlierfactor">https://github.com/dounpct/soc-ml-api-localoutlierfactor</a>.</li></ul><p><strong>CICD</strong></p><ul><li>I have create Jenkins job.</li><li>Create Jenkinsfile to run pipeline to keep Model in Mlflow and gen report</li></ul><pre>MLFLOW_MINIO_FOLDER=env.MLFLOW_MINIO_FOLDER<br>MLFLOW_TRAINING_FILE_LIMIT=env.MLFLOW_TRAINING_FILE_LIMIT<br><br>pipeline <br>{<br>    agent <br>    {<br>        node <br>        {<br>            label &quot;jenkins-python&quot;<br>        }       <br>    }<br><br>    environment {<br>        MLFLOW_TRACKING_USERNAME = credentials(&#39;MLFLOW_USER&#39;)<br>        MLFLOW_TRACKING_PASSWORD = credentials(&#39;MLFLOW_PASSWORD&#39;)<br>    }<br>    <br>    stages<br>    {<br>        <br>        stage(&#39;PrePare ENV&#39;) <br>        { <br>            steps <br>            {<br>                script <br>                {<br>                    container(&quot;python&quot;) <br>                    {<br>                        sh &quot;python --version&quot;            <br>                        sh &quot;pip install -r requirements.txt&quot;                                                                                                 <br>                    }<br>                }<br>            }<br>        }         <br>        stage(&#39;PrePare DataSet&#39;) <br>        { <br>            steps <br>            {<br>                script <br>                {<br>                    container(&quot;minio-mc&quot;) <br>                    {<br>                        sh &quot;mc -v&quot;<br>                        withCredentials([usernamePassword(credentialsId: &#39;ADS_AWS_CREDENTIAL&#39;, passwordVariable: &#39;password&#39;, usernameVariable: &#39;username&#39;)])     <br>                        {<br>                            sh &quot;mc alias set myminio https://minio.rtarf-prod.its-software-services.com/ ${username} ${password}&quot;<br>                            sh &quot;mkdir rawdata&quot;<br>                            sh &quot;mkdir images&quot;<br>                            <br>                            cmd = &quot;&quot;&quot;mc ls myminio/rtarf-ml/${MLFLOW_MINIO_FOLDER}/ --json | jq .key | sed &#39;s/&quot;//g&#39;&quot;&quot;&quot;<br>                            listFile = sh(script: cmd, returnStdout: true)<br><br>                            def lines = listFile.split(&#39;\n&#39;)<br>                            def i = 0<br>                            def limit = MLFLOW_TRAINING_FILE_LIMIT.trim().toInteger()<br>                            for (String line: lines)<br>                            {   <br>                                i++<br>                                sh &quot;mc cp myminio/rtarf-ml/${MLFLOW_MINIO_FOLDER}/${line} ./rawdata/&quot;<br>                                if (i &gt;= limit)<br>                                {<br>                                    break<br>                                }<br>                            }<br><br>                            // sh &quot;mc cp --recursive  myminio/rtarf-ml/${MLFLOW_MINIO_FOLDER}/ ./rawdata/&quot;<br>                            sh &quot;ls -alrt ./rawdata/&quot;<br>                            <br>                            cmd = &quot;ls ./rawdata/ | wc -l&quot;<br>                            countFile = sh(script: cmd, returnStdout: true)<br>                            println(&quot;countFile: ${countFile}&quot;)<br>                            currentBuild.description = &quot;folder:${MLFLOW_MINIO_FOLDER}/${MLFLOW_TRAINING_FILE_LIMIT}/${countFile}&quot;<br>                        }                                                                            <br>                    }<br>                }<br>            }<br>        }         <br>        stage(&#39;Training Model ADS-ANOMALY-DEST-COUNTRY-PORT&#39;) <br>        { <br>            steps <br>            {<br>                script <br>                {<br>                    container(&quot;python&quot;) <br>                    {<br>                        sh &quot;python -u train-ads-anomaly-dest-country-port.py ${env.BUILD_URL}console ${MLFLOW_MINIO_FOLDER} ${MLFLOW_TRAINING_FILE_LIMIT} ${env.BUILD_ID}&quot;<br>                    }<br>                    container(&quot;minio-mc&quot;) <br>                    {<br>                        withCredentials([usernamePassword(credentialsId: &#39;AWS_CREDENTIAL&#39;, passwordVariable: &#39;password&#39;, usernameVariable: &#39;username&#39;)])     <br>                        {<br>                            sh &quot;mc alias set ml-minio https://minio-api.rtarf-ml.its-software-services.com/ ${username} ${password}&quot;<br>                            <br>                            sh &quot;mc cp --recursive images/ ml-minio/ml-report/train-ads-anomaly-dest-country-port/${env.BUILD_ID}/&quot;<br>                            <br>                            sh &quot;mc cp report.html ml-minio/ml-report/train-ads-anomaly-dest-country-port/${env.BUILD_ID}/&quot;<br><br>                            println(&quot;report : https://minio-api.rtarf-ml.its-software-services.com/ml-report/train-ads-anomaly-dest-country-port/${env.BUILD_ID}/report.html&quot;)<br>                        }<br>                    }<br>                }<br>            }<br>        }         <br>    }<br>}</pre><p><strong>Dockerfile for Serving Model</strong></p><pre>FROM python:3.9<br><br>ENV HOME=&quot;/root&quot;<br>WORKDIR ${HOME}<br><br>RUN pip install google-cloud-storage<br><br>COPY requirements.txt requirements.txt<br>RUN pip install -r requirements.txt<br><br>ENV MODEL_URI ${MODEL_URI}<br>ENV SERVING_PORT ${SERVING_PORT}<br><br>COPY serving.sh /serving.sh<br><br>CMD [ &quot;/bin/bash&quot;, &quot;/serving.sh&quot; ]<br># CMD [ &quot;sh&quot;, &quot;-c&quot;, &quot;mlflow models serve --model-uri $MODEL_URI -h 0.0.0.0 -p $SERVING_PORT --no-conda&quot;]</pre><p>I have github action to auto build mlflow serving model images to GCR</p><pre>name: Genuine<br><br>on:<br>  push:<br>    branches: [ develop, master ]<br>    tags: [&#39;v*.*.*&#39;]<br><br>env:<br>  GH_TOKEN: ${{ secrets.GH_TOKEN }}<br><br>jobs:<br>  deploy:<br>    needs: [ build1 ]<br>    runs-on: ubuntu-latest<br>    steps:<br>    - name: Line notification start<br>      uses: snow-actions/line-notify@v1.0.0<br>      with:<br>        access_token: ${{ secrets.LINE_ACCESS_TOKEN }}<br>        message: &quot;Start deploying [genuine] [${{ needs.build1.outputs.imageTag }}] to [${{ needs.build1.outputs.autoDeployEnv }}]...&quot;<br><br>    - name: show job status<br>      if: always()<br>      uses: snow-actions/line-notify@v1.0.0<br>      with:<br>        access_token: ${{ secrets.LINE_ACCESS_TOKEN }}<br>        message: &quot;Done deploying [genuine] [${{ needs.build1.outputs.imageTag }}] to [${{ needs.build1.outputs.autoDeployEnv }}]...&quot;<br><br>  build1:<br>    runs-on: ubuntu-latest<br>    strategy:<br>      matrix:<br>        service: [ ml-training-api ]<br>    outputs:<br>      imageTag: ${{ steps.prep.outputs.version }}<br>      autoDeployEnv: ${{ steps.prep.outputs.deployEnv }}<br>      autoDeployBranch: ${{ steps.prep.outputs.autoDeployBranch }}<br>    steps:<br>    - name: Checkout repo<br>      uses: actions/checkout@v2<br><br>    ...<br>    ...<br>    ...<br><br>    - name: Build and push images<br>      uses: docker/build-push-action@v3<br>      with:<br>        file: ${{ steps.prep.outputs.dockerFile }}<br>        push: true<br>        load: false<br>        tags: ${{ steps.prep.outputs.gcr_tags }}<br>        build-args: version=${{ steps.prep.outputs.version }}<br><br>    - name: show job status<br>      if: always()<br>      uses: snow-actions/line-notify@v1.0.0<br>      with:<br>        access_token: ${{ secrets.LINE_ACCESS_TOKEN }}<br>        message: &quot;Done building [${{matrix.service}}] [${{ steps.prep.outputs.version }}] with status [${{job.status}}]&quot;</pre><p>Serve Model in Cluster</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mlflow-ads-anomaly-dest-country-port<br>  labels:<br>    app: mlflow-ads-anomaly-dest-country-port<br>spec:<br>  selector:<br>    matchLabels:<br>      app: mlflow-ads-anomaly-dest-country-port<br>  template:<br>    metadata:<br>      labels:<br>        app: mlflow-ads-anomaly-dest-country-port<br>    spec:<br>      containers:<br>        - name: mlflow-serving<br>          image: &lt;gcr-url&gt;:&lt;gcr-tag&gt;<br>          env:<br>            - name: MODEL_URI<br>              value: &quot;s3://mlflow-artifacts/1/xxxxxxxxxxxxxx/artifacts/model&quot; #change here<br>            - name: SERVING_PORT<br>              value: &quot;8082&quot;          <br>            - name: MLFLOW_S3_ENDPOINT_URL<br>              value: &quot;https://minio-ml-hl.minio-ml.svc.cluster.local:9000&quot;          <br>            - name: MLFLOW_S3_IGNORE_TLS<br>              value: &quot;true&quot;     <br>          resources:<br>            limits:<br>              cpu: 2000m<br>              memory: 4000Mi<br>            requests:<br>              cpu: 500m<br>              memory: 500Mi<br>          envFrom:<br>          - secretRef:<br>              name: mlflow-app-secrets<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    app: mlflow-ads-anomaly-dest-country-port<br>  name: mlflow-ads-anomaly-dest-country-port<br>spec:<br>  ports:<br>  - name: http-web<br>    port: 8082<br>    protocol: TCP<br>    targetPort: 8082<br>  selector:<br>    app: mlflow-ads-anomaly-dest-country-port<br>  type: ClusterIP<br>---<br>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: mlflow-ads-anomaly-dest-country-port<br>spec:<br>  minReplicas: 3  <br>  maxReplicas: 10<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: mlflow-ads-anomaly-dest-country-port<br>  targetCPUUtilizationPercentage: 60</pre><p>This is only part of Serving Destination country and port so another model is anomaly time</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mlflow-ads-anomaly-time<br>  labels:<br>    app: mlflow-ads-anomaly-time<br>spec:<br>  selector:<br>    matchLabels:<br>      app: mlflow-ads-anomaly-time<br>  template:<br>    metadata:<br>      labels:<br>        app: mlflow-ads-anomaly-time<br>    spec:<br>      containers:<br>        - name: mlflow-serving<br>          image: &lt;gcr-url&gt;:&lt;gcr-tag&gt;<br>          env:<br>            - name: MODEL_URI<br>              value: &quot;s3://mlflow-artifacts/2/xxxxxxxxxxxxxxx/artifacts/model&quot; #change here selective-rat-864<br>            - name: SERVING_PORT<br>              value: &quot;8082&quot;          <br>            - name: MLFLOW_S3_ENDPOINT_URL<br>              value: &quot;https://minio-ml-hl.minio-ml.svc.cluster.local:9000&quot;          <br>            - name: MLFLOW_S3_IGNORE_TLS<br>              value: &quot;true&quot;     <br>          resources:<br>            limits:<br>              cpu: 2000m<br>              memory: 2000Mi<br>            requests:<br>              cpu: 800m<br>              memory: 800Mi<br>          envFrom:<br>          - secretRef:<br>              name: mlflow-app-secrets<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    app: mlflow-ads-anomaly-time<br>  name: mlflow-ads-anomaly-time<br>spec:<br>  ports:<br>  - name: http-web<br>    port: 8082<br>    protocol: TCP<br>    targetPort: 8082<br>  selector:<br>    app: mlflow-ads-anomaly-time<br>  type: ClusterIP<br>---<br>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: mlflow-ads-anomaly-time<br>spec:<br>  minReplicas: 1  <br>  maxReplicas: 3<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: mlflow-ads-anomaly-time<br>  targetCPUUtilizationPercentage: 60</pre><p><strong>Gateway</strong></p><p>I have create gateway for re-engineer before request to model serving. For example gateway need to check for what model to be redirect and how to re-engineer or encoding same as step in model training</p><pre>@app.route(&#39;/v5/gateway&#39;, methods=[&#39;POST&#39;])<br>def get_invocationsV5():<br>    headers = {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    }<br><br>    predictionList = []<br>    content = request.json<br><br>    runAdsCountryDst = (&#39;disable_predict_anomaly_dest_country&#39; not in content) or (content[&#39;disable_predict_anomaly_dest_country&#39;] != &#39;true&#39;)<br>    runAdsTime = (&#39;disable_predict_anomaly_time&#39; not in content) or (content[&#39;disable_predict_anomaly_time&#39;] != &#39;true&#39;)<br>    ads_country_dst_log = &quot;&quot;<br>    ads_ts_hh_log = &quot;&quot;<br>    foundFlag = False<br>    if (runAdsCountryDst and (&#39;ads_country_dst&#39; in content)):<br>        content_data = createDataAdsAnomalyDestCountryPort(content[&#39;ads_country_dst&#39;],content[&#39;ads_dst_port&#39;])<br>        print(content_data)<br>        ads_country_dst_log = &quot;ads_country_dst : &quot;,content[&#39;ads_country_dst&#39;],&quot;:&quot;,content[&#39;ads_dst_port&#39;]<br>        print(ads_country_dst_log)<br>        foundFlag = True<br>        try:<br>            resp = requests.post(<br>                url=&quot;http://%s:%s/invocations&quot; % (host_anomaly_des_country_port, port_anomaly_des_country_port),<br>                data=json.dumps({&quot;dataframe_split&quot;: content_data}),headers=headers,<br>            )<br>            responseData = {<br>                                &quot;subject&quot;: &quot;unsupervised_dst_country_anomaly&quot;,<br>                                &quot;result&quot;: dataPredictionToString(resp.json()[&quot;predictions&quot;][0])<br>                            }<br>            predictionList.append(responseData)<br>            print(ads_country_dst_log,&quot;-&quot;,resp.status_code)<br>        except Exception as e:<br>            errmsg = &quot;Caught exception attempting to call model endpoint: %s&quot; % e<br>            print(errmsg, end=&quot;&quot;)<br>            return resp.json()<br><br>    if (runAdsTime and (&#39;ads_ts_hh&#39; in content)):<br>        content_data = {&quot;data&quot;:[[ content[&#39;ads_ts_hh&#39;] ]]}<br>        ads_ts_hh_log = &quot;ads_ts_hh : &quot;,content[&#39;ads_ts_hh&#39;]<br>        print(ads_ts_hh_log)<br>        foundFlag = True<br>        try:<br>            resp = requests.post(<br>                url=&quot;http://%s:%s/invocations&quot; % (host_anomaly_time, port_anomaly_time),<br>                data=json.dumps({&quot;dataframe_split&quot;: content_data}),headers=headers,<br>            )<br>            responseData = {<br>                                &quot;subject&quot;: &quot;unsupervised_login_anomaly&quot;,<br>                                &quot;result&quot;: dataPredictionToString(resp.json()[&quot;predictions&quot;][0])<br>                            }<br>            predictionList.append(responseData)<br>            print(ads_ts_hh_log,&quot;-&quot;,resp.status_code)<br>        except Exception as e:<br>            errmsg = &quot;Caught exception attempting to call model endpoint: %s&quot; % e<br>            print(errmsg, end=&quot;&quot;)<br>            return resp.json()<br><br>    if (not foundFlag):<br>        print(&quot;request not invocate all ml&quot;)<br><br>    responsePredictData = {&quot;results&quot;: predictionList}<br>    jsonString = jsonify(responsePredictData)<br>    print(ads_country_dst_log,&quot;|&quot;, ads_ts_hh_log,&quot;|&quot;,responsePredictData)<br>    return jsonString</pre><p>Dockerfile</p><pre>FROM python:3.9<br><br>ENV PYTHONUNBUFFERED=1<br>ENV PYTHONIOENCODING=UTF-8<br><br># Create app directory<br>WORKDIR /app<br><br># Install app dependencies<br>COPY requirements-flask.txt ./<br><br>RUN pip install -r requirements-flask.txt<br><br># Bundle app source<br>COPY server.py ./<br>COPY sharelib.py ./<br><br>EXPOSE 5000<br>CMD [&quot;python&quot;, &quot;server.py&quot;]</pre><p>workflow GitHub Action</p><pre>name: Gateway<br><br>on:<br>  push:<br>    branches: [ master ]<br>    tags: [&#39;v*.*.*&#39;]<br><br><br>env:<br>  GH_TOKEN: ${{ secrets.GH_TOKEN }}<br><br>jobs:<br>  build1:<br>    runs-on: ubuntu-latest<br>    strategy:<br>      matrix:<br>        service: [ ml-training-gateway ]<br>    outputs:<br>      imageTag: ${{ steps.prep.outputs.version }}<br>      autoDeployEnv: ${{ steps.prep.outputs.deployEnv }}<br>      autoDeployBranch: ${{ steps.prep.outputs.autoDeployBranch }}<br>    steps:<br>    - name: Checkout repo<br>      uses: actions/checkout@v2<br><br>...<br>...</pre><p>Deploy to Cluster</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mlflow-gateway<br>  labels:<br>    app: mlflow-gateway<br>spec:<br>  selector:<br>    matchLabels:<br>      app: mlflow-gateway<br>  template:<br>    metadata:<br>      labels:<br>        app: mlflow-gateway<br>    spec:<br>      containers:<br>        - name: mlflow-gateway<br>          image: &lt;gcr-url&gt;:&lt;gcr-tag&gt;<br>          env:<br>            - name: gateway_port_ml<br>              value: &quot;5000&quot;                          <br>          # command: [&quot;/bin/sleep&quot;, &quot;3650d&quot;]      <br>          resources:<br>            limits:<br>              cpu: 1000m<br>              memory: 700Mi<br>            requests:<br>              cpu: 200m<br>              memory: 300Mi<br>          livenessProbe:<br>            failureThreshold: 3<br>            httpGet:<br>              path: /healthcheck<br>              port: 5000<br>              scheme: HTTP<br>            initialDelaySeconds: 0<br>            periodSeconds: 10<br>            successThreshold: 1<br>            timeoutSeconds: 2<br>          readinessProbe:<br>            failureThreshold: 3<br>            httpGet:<br>              path: /healthcheck<br>              port: 5000<br>              scheme: HTTP<br>            initialDelaySeconds: 0<br>            periodSeconds: 10<br>            successThreshold: 1<br>            timeoutSeconds: 2<br>          envFrom:<br>          - configMapRef:<br>              name: gateway-cfm<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    app: mlflow-gateway<br>  name: mlflow-gateway<br>spec:<br>  ports:<br>  - name: http-web<br>    port: 5000<br>    protocol: TCP<br>    targetPort: 5000<br>  selector:<br>    app: mlflow-gateway<br>  type: ClusterIP<br>---<br>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: mlflow-gateway<br>spec:<br>  minReplicas: 30<br>  maxReplicas: 40<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: mlflow-gateway<br>  targetCPUUtilizationPercentage: 60</pre><p><strong>Serving with Gateway</strong></p><pre>curl -X POST -H &quot;Content-Type:application/json&quot; \<br>--data \<br>&#39;{&quot;@timestamp&quot;:&quot;2023-10-10T03:20:21.727444Z&quot;,&quot;ads_dst_port&quot;:&quot;53&quot;,...,&quot;ads_country_dst&quot;:&quot;United States&quot;,&quot;ads_ts_hh&quot;:&quot;1&quot;}&#39; \<br>http://&lt;GatewayURL&gt;/v5/gateway</pre><pre>{&quot;results&quot;:<br>  [<br>    {&quot;result&quot;:&quot;Normally&quot;,&quot;subject&quot;:&quot;unsupervised_dst_country_anomaly&quot;},<br>    {&quot;result&quot;:&quot;Anomaly&quot;,&quot;subject&quot;:&quot;unsupervised_login_anomaly&quot;}<br>  ]<br>}</pre><p>After we run test request from Metalog system. It can handle request for while but because a lot of traffic. HPA of deployment scale to high and consume a lot of resource and pod restart often because healthcheck can’t probe in time.</p><p>We have discuss in our team to decide cache in metalog system for 5 minute before send request to api gateway. if cache hit (memcache check that already for result in cache then update back to metalog by don’t need to send request to ML). Everything fine resource can scale down to min and only a little restart for gateway pod.</p><ul><li>Have fun !!!</li><li>I hope this topic may make some idea to someone</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422c9228eb20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Work around cannot scale pod because error npm ERR!Your]]></title>
            <link>https://dounpct.medium.com/work-around-cannot-scale-pod-because-error-npm-err-34a58d0b6b84?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/34a58d0b6b84</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 06:04:12 GMT</pubDate>
            <atom:updated>2023-12-04T06:07:26.510Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Work around cannot scale pod because error npm ERR!Your cache folder contains root-owned files, due to a bug in … with production in OpenShift and GKE</strong></h3><p>Yesterday I have join in incident about pre-scale resource for event in weekend.</p><p>The incident is can not scale resource with a lot of application in production environment. for example application set min 10 pod and max 20 pod then error with all new pod when set min to 40 max 80 pod.</p><p>When check error in each new pod.</p><pre>npm ERR! code EACCES<br>npm ERR! syscall mkdir<br>npm ERR! path /.npm<br>npm ERR! errno -13<br>npm ERR!<br>npm ERR! Your cache folder contains root-owned files, due to a bug in<br>npm ERR! previous versions of npm which has since been addressed.<br>npm ERR!<br>npm ERR! To permanently fix this problem, please run:<br>npm ERR! sudo chown -R 1001:0 &quot;/.npm&quot;<br><br>npm ERR! A complete log of this run can be found in:</pre><p>I know it may be about permission to write directory .npm . I try to search this error in search engine that have many solution such as</p><ul><li>sudo chown -R 1001:0 “/.npm” or sudo npm cache clean — force</li></ul><p>We have test change Dockerfile with set change user permission then can resolve problem when test in Development environment. But in incident meeting we have concern from our few DevLead.</p><ul><li>Why this error happen because image version tag don’t change for a while and we have scale every week not error.</li><li>We don’t need to build docker images (CI) now because this version tag still don’t pass all test.</li><li>DevTeam agree to apply new change Dockerfile to new version.</li></ul><p>So after concern from DevLead. I need to find other solution for work around in 2 hour before dead line to scale all resource to big event.</p><p>I have test to change user to 1000 or 0 for root in real time deployment. I have test in Development environment in OpenShift first.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: my-deployment<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: my-app<br>  template:<br>    metadata:<br>      labels:<br>        app: my-app<br>    spec:<br>      securityContext:<br>        runAsUser: 1000  # Update the UID as required.<br>        #runAsUser: 0  # Update the UID to root.<br>      containers:<br>      - name: my-app<br>        image: my-image:1.0<br>        ports:<br>        - containerPort: 8080</pre><p>Deployment can not apply in OpenShift. Because It need to add SecurityContextConstraints that OpenShift allow we can create in UI or command line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8b-Cu5G_u6efV7c1rJSMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGUeYt3TwPVdKgm-61fUFA.png" /></figure><p>or</p><pre>kind: SecurityContextConstraints<br>apiVersion: security.openshift.io/v1<br>metadata:<br>  name: run-as-root<br>allowPrivilegedContainer: true<br>runAsUser:<br>  type: RunAsAny<br>seLinuxContext:<br>  type: MustRunAs<br>fsGroup:<br>  type: MustRunAs<br>supplementalGroups:<br>  type: RunAsAny<br>users:<br>- system:serviceaccount:myproject:default</pre><p>note: change myproject with our project or namespace. and default if you set serviceaccount not default.</p><p>After set SecurityContextConstraints deployement can apply and pod can scale for test in Development environment. I need to make sure step to do repeat in Alpha and PreProduction environment that great.</p><p>I show good result in non-production environments with all attend. everyone agree to apply for production.</p><p>Production is go well to apply too. So let apply to all service that impact in Openshift.</p><p>For GKE error is same and can apply with same work around</p><pre>securityContext:<br>  runAsUser: 1000<br><br>or<br><br>securityContext:<br>  runAsUser: 0</pre><p>without setting for SecurityContextConstraints.</p><p>Today our workaround finish in time. I have great experience in my DevOps skill problem solving so much.</p><p>I hope this event may help some one.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>ref:</p><ul><li><a href="https://github.com/npm/cli/issues/5114">[BUG] npm incorrectly assumes existence of root-owned files on Termux · Issue #5114 · npm/cli</a></li><li><a href="https://medium.com/@samstickkz/title-fixing-npm-eacces-error-cache-folder-permission-issues-on-macos-35b7609cf868">Title: Fixing npm EACCES Error: Cache Folder Permission Issues on macOS</a></li><li><a href="https://stackoverflow.com/questions/59437833/error-your-cache-folder-contains-root-owned-files-due-to-a-bug-in-previous-ver">Error &quot;Your cache folder contains root-owned files, due to a bug in previous versions of npm&quot; while &quot;npx create-react-app example_app&quot;</a></li></ul><p><a href="https://reactgo.com/npm-missing-write-access/">https://reactgo.com/npm-missing-write-access/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34a58d0b6b84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mlflow with Helm and serve Train Model on kubernetes]]></title>
            <link>https://dounpct.medium.com/mlflow-with-helm-and-serve-train-model-on-kubernetes-77b4c605a967?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/77b4c605a967</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 11:35:35 GMT</pubDate>
            <atom:updated>2023-08-06T11:45:50.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 7: Serve Model API on Cluster</p><p><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-9b6338babc6c">Part 1: Install Mlflow on Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-ae9831982548">Part 2: Train example model and keep in Mlflow Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-671b55fc9780">Part 3: Expose example api on Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-2d59fec98dd1">Part 4: API Transform for Model API</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-c835139c4237">Part 5: Install Mlflow on GKE Cluster with helm</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-1d6441277965">Part 6: Keep Model in Mlflow remote Cluster</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-77b4c605a967">Part 7: Serve Model API on Cluster</a></p><p>In this topic I will show how to serve model with api server</p><p><strong>Build Model Images</strong></p><ul><li>Create Dockerfile</li></ul><pre>FROM python:3.9<br><br>ENV HOME=&quot;/root&quot;<br>WORKDIR ${HOME}<br><br># RUN pip install mlflow==2.1.1 google-cloud-storage pathlib==1.0.1 lz4==3.1.3 psutil==5.9.0 typing-extensions==4.3.0 cloudpickle==2.2.1<br>RUN pip install google-cloud-storage<br><br>COPY requirements.txt requirements.txt<br>RUN pip install -r requirements.txt<br><br>ENV MODEL_URI ${MODEL_URI}<br>ENV SERVING_PORT ${SERVING_PORT}<br><br># RUN apt-get install -y git<br># RUN git clone --depth=1 https://github.com/pyenv/pyenv.git .pyenv<br># ENV PYENV_ROOT=&quot;${HOME}/.pyenv&quot;<br># ENV PATH=&quot;${PYENV_ROOT}/shims:${PYENV_ROOT}/bin:${PATH}&quot;<br><br>COPY serving.sh /serving.sh<br><br>CMD [ &quot;/bin/bash&quot;, &quot;/serving.sh&quot; ]<br># CMD [ &quot;sh&quot;, &quot;-c&quot;, &quot;mlflow models serve --model-uri $MODEL_URI -h 0.0.0.0 -p $SERVING_PORT --no-conda&quot;]</pre><ul><li>Create requirements.txt</li></ul><pre>mlflow==2.1.1<br>pathlib==1.0.1<br>lz4==3.1.3 <br>psutil==5.9.0 <br>typing-extensions==4.3.0 <br>cloudpickle==2.2.1</pre><ul><li>Create serving.sh</li></ul><pre>#!/bin/sh<br><br>mlflow models serve --model-uri $MODEL_URI -h 0.0.0.0 -p $SERVING_PORT --no-conda</pre><ul><li>All code here: <a href="https://github.com/dounpct/soc-ml-api">https://github.com/dounpct/soc-ml-api</a></li><li>Build images</li></ul><pre>docker build -t mlflow .</pre><ul><li>Push images to gcr</li></ul><pre>docker tag mlflow:latest asia.gcr.io/gcp-devops/devops/mlflow_serving:latest<br>docker push asia.gcr.io/gcp-devops/devops/mlflow_serving:latest</pre><p>Note: please create CI with your tools such as Jenkins, Cloud Build , GitHub Action and so on.</p><p><strong>Deploy Images with ArgoCD</strong></p><ul><li>Create application mlflow-app</li></ul><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: mlflow-app<br>spec:<br>  project: mlflow<br>  source: <br>    repoURL: &#39;https://github.com/dounpct/argocd-deployment.git&#39;<br>    path: mlflow-app<br>    targetRevision: master<br>    plugin: {}<br>  destination:<br>    server: &#39;https://kubernetes.default.svc&#39;<br>    namespace: mlflow-app<br>  syncPolicy:<br>    syncOptions:<br>      - CreateNamespace=true</pre><ul><li>Create folder mlflow-app</li><li>Create folder plugin and empty file cmp-plugin-yaml.yaml. It because mlflow-app will be only yaml folder and need cmp-plugin-yaml.yaml for letting ArgoCD know for render plugin.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U66_jKmDtk1v0Fjk1b0QtQ.png" /></figure><ul><li>Create ingress.yaml</li></ul><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: ingress-with-auth-mlflow-app<br>  annotations:<br>    # type of authentication<br>    nginx.ingress.kubernetes.io/auth-type: basic<br>    # name of the secret that contains the user/password definitions<br>    nginx.ingress.kubernetes.io/auth-secret: basic-auth<br>    # message to display with an appropriate context why the authentication is required<br>    nginx.ingress.kubernetes.io/auth-realm: &#39;Authentication Required&#39;<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>  - host: nginx-auth-test.local.net<br>    http:<br>      paths:<br>      - path: /invocations<br>        pathType: Prefix<br>        backend:<br>          service: <br>            name: mlflow-serving<br>            port: <br>              number: 8082</pre><ul><li>Create secret.yaml</li></ul><pre>apiVersion: v1<br>kind: Secret<br>type: Opaque<br>metadata:<br>  name: gcsfs-creds<br>data:<br>  keyfile.json: &lt;path:projects/362159383816/secrets/google_credentials_json#google_credentials_json | base64encode&gt;<br>---<br>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: gcr-authen<br>type: kubernetes.io/dockerconfigjson<br>data:<br>  .dockerconfigjson: &lt;path:projects/362159383816/secrets/GCR_DOCKERCONFIGJSON#GCR_DOCKERCONFIGJSON | base64encode&gt;<br>---<br>apiVersion: v1<br>kind: Secret<br>type: Opaque<br>metadata:<br>  name: basic-auth<br>data:<br>  auth: &lt;path:projects/362159383816/secrets/tdg_ingress_basic_authen#tdg_ingress_basic_authen | base64encode&gt;<br>  user: &lt;path:projects/362159383816/secrets/tdg_ingress_basic_authen_user#tdg_ingress_basic_authen_user | base64encode&gt;<br>  password: &lt;path:projects/362159383816/secrets/tdg_ingress_basic_authen_password#tdg_ingress_basic_authen_password | base64encode&gt;</pre><ul><li>Go to GCS and copy gsutil URI</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*58qM7tRdOPP1h_it2EecsA.png" /></figure><ul><li>Create application.yaml</li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mlflow-serving<br>  labels:<br>    app: serve-ML-model-mlflow<br><br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: mlflow-serving<br>  template:<br>    metadata:<br>      labels:<br>        app: mlflow-serving<br><br>    spec:<br>      containers:<br>        - name: mlflow-serving<br>          image: asia.gcr.io/xxxxxxxx/mlflow_serving:latest #change here<br>          env:<br>            - name: MODEL_URI<br>              value: &quot;gs://xxxxxxxxxx/artifacts/model&quot; #change here<br>            - name: SERVING_PORT<br>              value: &quot;8082&quot;<br>            - name: GOOGLE_APPLICATION_CREDENTIALS<br>              value: &quot;/etc/secrets/keyfile.json&quot;<br>          volumeMounts:<br>            - name: gcsfs-creds<br>              mountPath: &quot;/etc/secrets&quot;<br>              readOnly: true<br>          resources:<br>            limits:<br>              cpu: 1000m<br>              memory: 600Mi<br>            requests:<br>              cpu: 500m<br>              memory: 300Mi<br>      imagePullSecrets:<br>      - name: gcr-authen<br>      <br>      volumes:<br>        - name: gcsfs-creds<br>          secret:<br>            secretName: gcsfs-creds<br>            items:<br>              - key: keyfile.json<br>                path: keyfile.json<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    app: mlflow-serving<br>  name: mlflow-serving<br>spec:<br>  ports:<br>  - name: http-web<br>    port: 8082<br>    protocol: TCP<br>    targetPort: 8082<br>  selector:<br>    app: mlflow-serving<br>  type: ClusterIP<br>---<br>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: mlflow-serving<br>spec:<br>  minReplicas: 1  <br>  maxReplicas: 3<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: mlflow-serving<br>  targetCPUUtilizationPercentage: 60</pre><ul><li>All code here: <a href="https://github.com/dounpct/argocd-deployment">https://github.com/dounpct/argocd-deployment</a></li><li>Commit to repo and let ArgoCD syn</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aod48WujtnXOVehhzHqGKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIqJqziIlMtG8Nor-l7pIg.png" /></figure><ul><li>Check application on GKE</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*HuDvF00M7xPlEmfa4YSv0w.png" /></figure><ul><li>Check ingress</li></ul><pre>kubectl get ing -n mlflow-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*dW5enIOt8vtQ77hDgkwc8w.png" /></figure><ul><li>Test API</li></ul><pre>curl -X POST -H &quot;Content-Type:application/json&quot;                     \<br>    --data &quot;{\&quot;dataframe_split\&quot;: {\&quot;data\&quot;:[[                          \<br>        0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  <br>        0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  <br>        0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,<br>        0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  <br>        0.0,  0.0,  1.0,  0.0]]}}&quot;                                      \<br>    http://nginx-auth-test.local.com/invocations -u &#39;ingress_user:xxxxxxxxxxxxxxxxxxxxxx&#39; | jq</pre><pre>### RESULT ###<br>{<br>    &quot;predictions&quot;: [<br>        &quot;yes&quot;<br>    ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0CnS5-CGH1ENrr6K_VtJw.png" /></figure><ul><li>Great as you see we already have API that can scale with HPA to serve traffic to predict request</li><li>Note I have mlflow both on GKE (GCS and S3 Minio) so this is for Minio</li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mlflow-serving<br>  labels:<br>    app: serve-ML-model-mlflow<br>spec:<br>  selector:<br>    matchLabels:<br>      app: mlflow-serving<br>  template:<br>    metadata:<br>      labels:<br>        app: mlflow-serving<br>    spec:<br>      containers:<br>        - name: mlflow-serving<br>          image: gcr.io/xxxxxxxxxxx/ml-training-api:v0.0.5 #change here<br>          env:<br>            - name: MODEL_URI<br>              value: &quot;s3://mlflow/1/xxxxxxxxxxxxxxxxxxx/artifacts/model&quot; #change here<br>            - name: SERVING_PORT<br>              value: &quot;8082&quot;          <br>            - name: MLFLOW_S3_ENDPOINT_URL<br>              value: &quot;https://minio-ml-hl.minio-ml.svc.cluster.local:9000&quot;          <br>            - name: MLFLOW_S3_IGNORE_TLS<br>              value: &quot;true&quot;      <br>          resources:<br>            limits:<br>              cpu: 1000m<br>              memory: 600Mi<br>            requests:<br>              cpu: 500m<br>              memory: 300Mi<br>          envFrom:<br>          - secretRef:<br>              name: mlflow-app-secrets<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    app: mlflow-serving<br>  name: mlflow-serving<br>spec:<br>  ports:<br>  - name: http-web<br>    port: 8082<br>    protocol: TCP<br>    targetPort: 8082<br>  selector:<br>    app: mlflow-serving<br>  type: ClusterIP<br>---<br>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: mlflow-serving<br>spec:<br>  minReplicas: 1  <br>  maxReplicas: 3<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: mlflow-serving<br>  targetCPUUtilizationPercentage: 60</pre><ul><li>Have fun !!!</li></ul><h3><strong><em>This is End of “Mlflow with Helm and serve Train Model on kubernetes”</em></strong></h3><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77b4c605a967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mlflow with Helm and serve Train Model on kubernetes]]></title>
            <link>https://dounpct.medium.com/mlflow-with-helm-and-serve-train-model-on-kubernetes-1d6441277965?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6441277965</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 10:26:03 GMT</pubDate>
            <atom:updated>2023-08-06T11:37:47.779Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 6: Keep Model in Mlflow remote Cluster</p><p><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-9b6338babc6c">Part 1: Install Mlflow on Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-ae9831982548">Part 2: Train example model and keep in Mlflow Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-671b55fc9780">Part 3: Expose example api on Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-2d59fec98dd1">Part 4: API Transform for Model API</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-c835139c4237">Part 5: Install Mlflow on GKE Cluster with helm</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-1d6441277965">Part 6: Keep Model in Mlflow remote Cluster</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-77b4c605a967">Part 7: Serve Model API on Cluster</a></p><p>After we have Mlflow Tracking on GKE Cluster then we will train ML and keep it to Mlflow Tracking on GKE Cluster.</p><ul><li>Open Train example model from Part2: Train example model and keep in Mlflow Local Machine</li><li>Code : <a href="https://github.com/dounpct/soc-ml-api">https://github.com/dounpct/soc-ml-api</a></li><li>Open mlflow tracking server on GKE</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*TMIL7myQb1JsBDas2oOSTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ogTqxezdzvZR6cih5KD5lA.png" /></figure><ul><li>Add New Experiments: soc-ml-default</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*tjjxu1I7DfsKg-2VcHFkMA.png" /></figure><ul><li>Open Train.py</li><li>In terminal export</li></ul><pre>export MLFLOW_TRACKING_URI=http://mlflow-tracking.domain.com<br>export MLFLOW_TRACKING_USERNAME=user <br>export MLFLOW_TRACKING_PASSWORD=pwd</pre><ul><li>Run Train.py</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCjZLbtszcA89J7PyDECrg.png" /></figure><ul><li>Check On Mlflow Tracking Server</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zkznQopUhFK5ufIhMW_I2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkJRTYf0pasMTSZzwys6VQ.png" /></figure><ul><li>Have fun !!!</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6441277965" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mlflow with Helm and serve Train Model on kubernetes]]></title>
            <link>https://dounpct.medium.com/mlflow-with-helm-and-serve-train-model-on-kubernetes-c835139c4237?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/c835139c4237</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 11:02:09 GMT</pubDate>
            <atom:updated>2023-08-06T11:38:24.122Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 5: Install Mlflow on GKE Cluster with helm</p><p><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-9b6338babc6c">Part 1: Install Mlflow on Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-ae9831982548">Part 2: Train example model and keep in Mlflow Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-671b55fc9780">Part 3: Expose example api on Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-2d59fec98dd1">Part 4: API Transform for Model API</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-c835139c4237">Part 5: Install Mlflow on GKE Cluster with helm</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-1d6441277965">Part 6: Keep Model in Mlflow remote Cluster</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-77b4c605a967">Part 7: Serve Model API on Cluster</a></p><p><strong>Create GKE Cluster</strong></p><ul><li>You can create any GKE cluster or use your exist GKE</li></ul><p><strong>Overview Mlflow In GKE</strong></p><p>As you know I like to install every opensource with helm and syn with ArgoCD that already have integrate vault plugin. So let start</p><p>Requirement</p><ul><li>When run Mlflow in kubernetes we need a database. So I choose postgresql</li><li>We will keep Model in GCS</li><li>You can see how to install ArgoCD with my Article : <a href="https://dounpct.medium.com/argocd-argocd-vault-plugin-20d28f03316c">https://dounpct.medium.com/argocd-argocd-vault-plugin-20d28f03316c</a></li><li>Chart here : <a href="https://artifacthub.io/packages/helm/community-charts/mlflow">mlflow 0.7.19 · community-charts/community-charts (artifacthub.io)</a></li></ul><p><strong>Install Postgresql</strong></p><p>All source code can be found here <a href="https://github.com/dounpct/argocd-deployment">dounpct/argocd-deployment (github.com)</a></p><ul><li>create kind: AppProject in project.yaml in folder applications</li></ul><pre>apiVersion: argoproj.io/v1alpha1<br>kind: AppProject<br>metadata:<br>  name: database<br>spec:<br>  clusterResourceWhitelist:<br>  - group: &#39;*&#39;<br>    kind: &#39;*&#39;<br>  destinations:<br>  - namespace: &#39;*&#39;<br>    server: https://kubernetes.default.svc<br>  sourceRepos:<br>  - &#39;*&#39;</pre><ul><li>create apps-postgresql.yaml in folder applications</li></ul><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: postgresql<br>spec:<br>  project: database<br>  source:<br>    path: &#39;postgresql&#39;<br>    repoURL: &#39;https://github.com/dounpct/argocd-deployment.git&#39;<br>    targetRevision: master<br>    plugin:<br>      env:<br>        - name:  INIT_ARGS<br>          value: &quot;helm dep update&quot;<br>        - name:  ARG_PARAMETERS<br>          value: &quot;helm template postgresql -n postgresql . -f values/values.yaml &quot;<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: postgresql<br>  syncPolicy:<br>    syncOptions:<br>      - CreateNamespace=true</pre><ul><li>Chart.yaml</li></ul><pre>apiVersion: v2<br>name: helm-postgresql<br>description: A Helm chart for Kubernetes<br><br># A chart can be either an &#39;application&#39; or a &#39;library&#39; chart.<br>#<br># Application charts are a collection of templates that can be packaged into versioned archives<br># to be deployed.<br>#<br># Library charts provide useful utilities or functions for the chart developer. They&#39;re included as<br># a dependency of application charts to inject those utilities and functions into the rendering<br># pipeline. Library charts do not define any templates and therefore cannot be deployed.<br>type: application<br><br># This is the chart version. This version number should be incremented each time you make changes<br># to the chart and its templates, including the app version.<br># Versions are expected to follow Semantic Versioning (https://semver.org/)<br>version: 1.0.1<br><br># This is the version number of the application being deployed. This version number should be<br># incremented each time you make changes to the application. Versions are not expected to<br># follow Semantic Versioning. They should reflect the version the application is using.<br>appVersion: 1.16.0<br>dependencies:<br>  - name: postgresql<br>    version: 12.2.3<br>    repository: https://charts.bitnami.com/bitnami</pre><pre>cd postgresql<br>helm dep update</pre><ul><li>add vaules/values.yaml</li></ul><pre>postgresql:<br>  global:<br>    postgresql:<br>      auth:<br>        postgresPassword: &lt;path:projects/362159383816/secrets/postgresql-admin-password#postgresql-admin-password&gt;<br>        database: &quot;mlflow&quot;</pre><ul><li>test render postgresql in same concept with ArgoCD and should no error</li></ul><pre>helm template postgresql -n postgresql . -f values/values.yaml | argocd-vault-plugin generate -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYoZtD9SlVUR497iWT6BWg.png" /></figure><ul><li>Commit code to git and let ArgoCD deploy</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ok6JLWMW5y5vOAGjlDZY8w.png" /></figure><ul><li>Great</li></ul><p><strong>Install Mlflow with ArgoCD</strong></p><p>All source code can be found here <a href="https://github.com/dounpct/argocd-deployment">dounpct/argocd-deployment (github.com)</a></p><ul><li>create kind: AppProject in project.yaml in folder applications</li></ul><pre>apiVersion: argoproj.io/v1alpha1<br>kind: AppProject<br>metadata:<br>  name: mlflow<br>spec:<br>  clusterResourceWhitelist:<br>  - group: &#39;*&#39;<br>    kind: &#39;*&#39;<br>  destinations:<br>  - namespace: mlflow<br>    server: https://kubernetes.default.svc<br>  sourceRepos:<br>  - &#39;*&#39;</pre><ul><li>create apps-ml.yaml in folder applications</li></ul><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: mlflow<br>spec:<br>  project: mlflow<br>  source:<br>    path: &#39;mlflow&#39;<br>    repoURL: &#39;https://github.com/dounpct/argocd-deployment.git&#39;<br>    targetRevision: master<br>    plugin:<br>      env:<br>        - name:  INIT_ARGS<br>          value: &quot;helm dep update&quot;<br>        - name:  ARG_PARAMETERS<br>          value: &quot;helm template mlflow -n mlflow . -f values/values.yaml &quot;<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: mlflow<br>  syncPolicy:<br>    syncOptions:<br>      - CreateNamespace=true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOS7daHDJSGssaib9_91Cg.png" /></figure><ul><li>create forlder mlflow that have same structure with folder argocd , templates , values/vaules.yaml , Chart.yaml values.yaml</li><li>check version charts mlflow</li></ul><pre>helm repo add community-charts https://community-charts.github.io/helm-charts<br>helm repo update<br>helm search repo community-charts/mlflow</pre><ul><li>Chart.yaml</li></ul><pre>apiVersion: v2<br>name: helm-mlflow<br>description: A Helm chart for Kubernetes<br><br># A chart can be either an &#39;application&#39; or a &#39;library&#39; chart.<br>#<br># Application charts are a collection of templates that can be packaged into versioned archives<br># to be deployed.<br>#<br># Library charts provide useful utilities or functions for the chart developer. They&#39;re included as<br># a dependency of application charts to inject those utilities and functions into the rendering<br># pipeline. Library charts do not define any templates and therefore cannot be deployed.<br>type: application<br><br># This is the chart version. This version number should be incremented each time you make changes<br># to the chart and its templates, including the app version.<br># Versions are expected to follow Semantic Versioning (https://semver.org/)<br>version: 0.0.1<br><br># This is the version number of the application being deployed. This version number should be<br># incremented each time you make changes to the application. Versions are not expected to<br># follow Semantic Versioning. They should reflect the version the application is using.<br>appVersion: 0.0.1<br>dependencies:<br>  - name: mlflow <br>    version: 0.7.19<br>    repository: https://community-charts.github.io/helm-charts</pre><pre>cd mlflow<br>helm dep update</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*UNvhGVsvQR5d4B_rk_PSlg.png" /></figure><ul><li>Add secret.yaml</li></ul><pre>apiVersion: v1<br>kind: Secret<br>type: Opaque<br>metadata:<br>  name: google-credentials-creds<br>data:<br>  google_credentials.json: &lt;path:projects/362159383816/secrets/google_credentials_json#google_credentials_json | base64encode&gt;<br>---<br>apiVersion: v1<br>kind: Secret<br>type: Opaque<br>metadata:<br>  name: basic-auth<br>data:<br>  auth: &lt;path:projects/362159383816/secrets/tdg_ingress_basic_authen#tdg_ingress_basic_authen | base64encode&gt;<br>  user: &lt;path:projects/362159383816/secrets/tdg_ingress_basic_authen_user#tdg_ingress_basic_authen_user | base64encode&gt;<br>  password: &lt;path:projects/362159383816/secrets/tdg_ingress_basic_authen_password#tdg_ingress_basic_authen_password | base64encode&gt;</pre><ul><li>Add ingress.yaml with basic Authen</li></ul><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: ingress-with-auth-mlflow<br>  annotations:<br>    # type of authentication<br>    nginx.ingress.kubernetes.io/auth-type: basic<br>    # name of the secret that contains the user/password definitions<br>    nginx.ingress.kubernetes.io/auth-secret: basic-auth<br>    # message to display with an appropriate context why the authentication is required<br>    nginx.ingress.kubernetes.io/auth-realm: &#39;Authentication Required&#39;<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>  - host: mlflow-tracking.domain.com<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service: <br>            name: mlflow<br>            port: <br>              number: 5000</pre><ul><li>add vaules/values.yaml</li></ul><pre>mlflow:  <br>  service:<br>    # -- Specifies what type of Service should be created<br>    type: ClusterIP<br>    # -- Default Service port<br>    port: 5000<br>    # -- Default Service name<br>    name: http<br>    # -- Additional service annotations<br>    annotations: {}<br><br>  backendStore:<br>    # -- Specifies if you want to run database migration<br>    databaseMigration: true<br><br>    # -- Add an additional init container, which checks for database availability<br>    databaseConnectionCheck: true<br><br>    postgres:<br>      # -- Specifies if you want to use postgres backend storage<br>      enabled: true<br>      # -- Postgres host address. e.g. your RDS or Azure Postgres Service endpoint<br>      host: &quot;postgresql.postgresql.svc.cluster.local&quot; # required<br>      # -- Postgres service port<br>      port: 5432 # required<br>      # -- mlflow database name created before in the postgres instance<br>      database: &quot;mlflow&quot; # required<br>      # -- postgres database user name which can access to mlflow database<br>      user: &quot;postgres&quot; # required<br>      # -- postgres database user password which can access to mlflow database<br>      password: &lt;path:projects/362159383816/secrets/postgresql-admin-password#postgresql-admin-password&gt; # required<br>      # -- postgres database connection driver. e.g.: &quot;psycopg2&quot;<br>      driver: &quot;&quot;<br>  artifactRoot:<br>    # -- Specifies if you want to enable proxied artifact storage access<br>    proxiedArtifactStorage: true<br>    gcs:<br>      # -- Specifies if you want to use Google Cloud Storage Mlflow Artifact Root<br>      enabled: true<br>      # -- Google Cloud Storage bucket name<br>      bucket: &quot;mlflow_gke_test_20230314&quot; # required<br>      # -- Google Cloud Storage bucket folder. If you want to use root level, please don&#39;t set anything.<br>      path: &quot;&quot; # optional<br>  <br>  # -- Extra environment variables<br>  extraEnvVars:<br>    GOOGLE_APPLICATION_CREDENTIALS: &quot;/app/config/google/google_credentials.json&quot;<br>    # MLFLOW_S3_IGNORE_TLS: true<br>    # MLFLOW_S3_UPLOAD_EXTRA_ARGS: &#39;{&quot;ServerSideEncryption&quot;: &quot;aws:kms&quot;, &quot;SSEKMSKeyId&quot;: &quot;1234&quot;}&#39;<br>    # AWS_DEFAULT_REGION: my_region<br>    # MLFLOW_S3_ENDPOINT_URL: http://1.2.3.4:9000<br>    # AWS_CA_BUNDLE: /some/ca/bundle.pem<br>    # MLFLOW_GCS_DEFAULT_TIMEOUT - Sets the standard timeout for transfer operations in seconds (Default: 60). Use -1 for indefinite timeout.<br>    # MLFLOW_GCS_UPLOAD_CHUNK_SIZE - Sets the standard upload chunk size for bigger files in bytes (Default: 104857600 ≙ 100MiB), must be multiple of 256 KB.<br>    # MLFLOW_GCS_DOWNLOAD_CHUNK_SIZE - Sets the standard download chunk size for bigger files in bytes (Default: 104857600 ≙ 100MiB), must be multiple of 256 K<br>  <br>  # -- Extra Volumes for the pod<br>  extraVolumes:<br>  - name: google-credentials-creds<br>    secret:<br>      secretName: google-credentials-creds<br><br>  # -- Extra Volume Mounts for the mlflow container<br>  extraVolumeMounts:<br>  - name: google-credentials-creds<br>    mountPath: /app/config/google<br>  </pre><p>Note we use : <a href="https://www.mlflow.org/docs/latest/tracking.html#scenario-5-mlflow-tracking-server-enabled-with-proxied-artifact-storage-access">MLflow Tracking — MLflow 2.4.1 documentation</a><br>It mean we use Tracking Server to be proxued to handle with both database (Postgres) and artifact storage access (GCS)</p><ul><li>Test render mlflow in same concept with ArgoCD and should no error and becuase I connect with Google secret manager</li></ul><pre>export GOOGLE_APPLICATION_CREDENTIALS=&quot;path-to-your-google-service-account-key/key.json&quot;<br>export AVP_TYPE=gcpsecretmanager</pre><pre>helm template mlflow -n mlflow . -f values/values.yaml | argocd-vault-plugin generate -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4NtCR-2Mv7Tim0YWGXm3g.png" /></figure><ul><li>Commit code to git and let ArgoCD deploy</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnrKwNC6V-fo_v4TVLJTUQ.png" /></figure><ul><li>Map ingress DNS to Nginx External load balancer</li><li>Open MLflow’s Tracking Server and fill user password</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5se2C5qzLSRm96Cf6us_w.png" /></figure><ul><li>Note for connect to AWS S3 Bucket (minio)</li></ul><pre>mlflow:<br>  artifactRoot:<br>    # -- Specifies if you want to enable proxied artifact storage access<br>    proxiedArtifactStorage: true<br>    s3:<br>      # -- Specifies if you want to use AWS S3 Mlflow Artifact Root<br>      enabled: true<br>      # -- S3 bucket name<br>      bucket: &quot;mlflow&quot; # required<br>      # -- S3 bucket folder. If you want to use root level, please don&#39;t set anything.<br>      path: &quot;&quot; # optional<br>      # -- AWS IAM user AWS_ACCESS_KEY_ID which has attached policy for access to the S3 bucket<br>      awsAccessKeyId: &quot;&quot; # (awsAccessKeyId and awsSecretAccessKey) or roleArn serviceaccount annotation required<br>      # -- AWS IAM user AWS_SECRET_ACCESS_KEY which has attached policy for access to the S3 bucket<br>      awsSecretAccessKey: &quot;&quot; # (awsAccessKeyId and awsSecretAccessKey) or roleArn serviceaccount annotation required<br>    <br>  # -- Extra environment variables<br>  extraEnvVars:<br>    # GOOGLE_APPLICATION_CREDENTIALS: &quot;/app/config/google/google_credentials.json&quot;<br>    MLFLOW_S3_IGNORE_TLS: true<br>    # MLFLOW_S3_UPLOAD_EXTRA_ARGS: &#39;{&quot;ServerSideEncryption&quot;: &quot;aws:kms&quot;, &quot;SSEKMSKeyId&quot;: &quot;1234&quot;}&#39;<br>    # AWS_DEFAULT_REGION: my_region<br>    MLFLOW_S3_ENDPOINT_URL: https://minio-ml-hl.minio-ml.svc.cluster.local:9000<br>    # AWS_CA_BUNDLE: /some/ca/bundle.pem<br>    # MLFLOW_GCS_DEFAULT_TIMEOUT - Sets the standard timeout for transfer operations in seconds (Default: 60). Use -1 for indefinite timeout.<br>    # MLFLOW_GCS_UPLOAD_CHUNK_SIZE - Sets the standard upload chunk size for bigger files in bytes (Default: 104857600 ≙ 100MiB), must be multiple of 256 KB.<br>    # MLFLOW_GCS_DOWNLOAD_CHUNK_SIZE - Sets the standard download chunk size for bigger files in bytes (Default: 104857600 ≙ 100MiB), must be multiple of 256 K<br><br>  # -- Extra secrets for environment variables<br>  extraSecretNamesForEnvFrom:<br>  - mlflow-secrets</pre><ul><li>Create secret mlflow-secrets that have credencial AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY for connect minio</li><li>Have fun!!!</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c835139c4237" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aws Lambda Nodejs serve http + ServerLess]]></title>
            <link>https://dounpct.medium.com/aws-lambda-nodejs-serve-http-serverless-f8727b93c787?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8727b93c787</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 19:28:50 GMT</pubDate>
            <atom:updated>2023-04-29T19:32:36.163Z</atom:updated>
            <content:encoded><![CDATA[<p>“Aws Lambda, Nodejs, http server, Serverless”</p><p>Long time ago that I have been DevOps engineer and need to maintain Cloud Function from Google Cloud. I think it ok simple. But few time that I have requirement from team vendor that implement application on AWS and they request to have simple api server to handle from webhook on cloud such as Jira and so on.</p><p><strong>Objective</strong></p><ul><li>Create first Lambda function with simple UI</li><li>Create express with package serverless-http</li><li>Create serverless + express</li></ul><p>Prerequisite</p><ul><li>Nodejs</li><li>AWS account with access to console</li></ul><h3>Create first Lambda function with simple UI</h3><ul><li>Login to AWS console</li><li>Services and Lambda</li><li>Click Create function button</li><li>Select Author from scratch</li><li>Function name : test-first-lambda</li><li>Runtime: Node.js 14.x or else</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UV99YgmFP-4NbeXSCLI1_Q.png" /></figure><ul><li>Click Advanced setting</li><li>Enable function URL</li><li>Auth type: NONE</li><li>Click Create function</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_75acu8HYN-vvvQ3Zhjc7g.png" /></figure><ul><li>Open URL</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*aRqNwAxPYJguw4rj-imWbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5xtKjjVfFSb-UVLlRaDPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDusBEsbu2Tb6jO-L60fnA.png" /></figure><ul><li>Simple let go on</li></ul><h3>Create express with package serverless-http</h3><ul><li>On your local machine</li><li>Create Folder: devops-test-express</li><li>Create file: index.js</li></ul><pre>const express = require(&#39;express&#39;);<br>const port = process.env.PORT || 3000;<br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    const text = &#39;{&quot;name&quot;:&quot;John&quot;, &quot;birth&quot;:&quot;1986-12-14&quot;, &quot;city&quot;:&quot;New York&quot;}&#39;;<br>    const obj = JSON.parse(text);<br>    console.log(obj)<br>    res.status(200)<br>    res.send(obj)<br>});<br><br>app.get(&#39;/healthcheck&#39;, (req, res) =&gt; {<br>    res.status(200)<br>    res.send(&#39;ok&#39;)<br>});<br><br>app.get(&#39;/create&#39;, (req, res) =&gt; {<br>    res.status(201)<br>    res.send(&#39;created&#39;)<br>});<br><br>app.listen(port, () =&gt; {<br>    console.log(`Server is listening on port ${port}.`);<br>});</pre><pre>npm init -y<br>npm install express --save<br>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhC7hZBu3Ls0Nf9K1M9IjQ.png" /></figure><ul><li>Test on localhost:3000</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*wzYGY_A0SOR-GVUlX0Zvzg.png" /></figure><ul><li>Add</li></ul><pre>const serverless = require(&#39;serverless-http&#39;);</pre><ul><li>And</li></ul><pre>exports.handler = serverless(app);</pre><ul><li>Set ENV for local and on Lambda. So</li></ul><pre>const express = require(&#39;express&#39;);<br>const serverless = require(&#39;serverless-http&#39;);<br>const port = process.env.PORT || 3000;<br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    const text = &#39;{&quot;name&quot;:&quot;John&quot;, &quot;birth&quot;:&quot;1986-12-14&quot;, &quot;city&quot;:&quot;New York&quot;}&#39;;<br>    const obj = JSON.parse(text);<br>    console.log(obj)<br>    res.status(200)<br>    res.send(obj)<br>});<br><br>app.get(&#39;/healthcheck&#39;, (req, res) =&gt; {<br>    res.status(200)<br>    res.send(&#39;ok&#39;)<br>});<br><br>app.get(&#39;/create&#39;, (req, res) =&gt; {<br>    res.status(201)<br>    res.send(&#39;created&#39;)<br>});<br><br>if (process.env.ENVIRONMENT === &#39;production&#39;) {<br>    exports.handler = serverless(app);<br>} else {<br>    app.listen(port, () =&gt; {<br>        console.log(`Server is listening on port ${port}.`);<br>    });<br>}</pre><pre>npm install serverless-http --save</pre><ul><li>Zip file</li></ul><pre>zip -r -y -q dist.zip .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*0Ce0_Cjr8nSfe22jImJIZg.png" /></figure><ul><li>Create new Lambda from scratch with same configuration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4X5lu8LLV_zRIq0wbSiZWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*C4ohU5C_LmrtMcGN5IxOkA.png" /></figure><ul><li>Click Upload from Button → .zip file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*aggIPdS41Gfo_lwBz9N8OQ.png" /></figure><ul><li>Choose your file and Save</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*Nh5hyQEeK7xAsR3MRfIT8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NP86F9ZajuMgYzlgsFIFNQ.png" /></figure><ul><li>ADD ENV</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUzQgysuVxd84Btwphjk4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*b7iN2bcjGfodhZ61YC-D3Q.png" /></figure><ul><li>Test URL</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*Xp6WvZHn7PHkeBLgSTXlrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*rG5svmPSBhygqDhXSgxOMQ.png" /></figure><h3><strong>Create serverless + express</strong></h3><ul><li>Install serverless : <a href="https://www.serverless.com/framework/docs/getting-started">https://www.serverless.com/framework/docs/getting-started</a></li></ul><pre>npm install -g serverless</pre><ul><li>Configuration to connect AWS that need</li></ul><pre> <br>export AWS_ACCESS_KEY_ID=&lt;your-key-here&gt;<br>export AWS_SECRET_ACCESS_KEY=&lt;your-secret-key-here&gt;</pre><ul><li>Create New Project with same express code</li></ul><pre>//index.js<br>const express = require(&#39;express&#39;);<br>const port = process.env.PORT || 3000;<br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    const text = &#39;{&quot;name&quot;:&quot;Sutee&quot;, &quot;love&quot;:&quot;Tech&quot;, &quot;job&quot;:&quot;DevOps&quot;}&#39;;<br>    const obj = JSON.parse(text);<br>    console.log(obj)<br>    res.status(200)<br>    res.send(obj)<br>});<br><br>app.get(&#39;/healthcheck&#39;, (req, res) =&gt; {<br>    res.status(200)<br>    res.send(&#39;ok&#39;)<br>});<br><br>app.get(&#39;/create&#39;, (req, res) =&gt; {<br>    res.status(201)<br>    res.send(&#39;created&#39;)<br>});<br><br><br>app.listen(port, () =&gt; {<br>    console.log(`Server is listening on port ${port}.`);<br>});</pre><pre>npm install aws-lambda-http-server --save</pre><pre>{<br>  &quot;name&quot;: &quot;devops-test-serverless-express&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;node index.js&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;aws-lambda-http-server&quot;: &quot;^0.2.7&quot;,<br>    &quot;express&quot;: &quot;^4.18.2&quot;<br>  }<br>}</pre><ul><li>Add aws-lambda.js</li></ul><pre>exports.proxy = require(&#39;aws-lambda-http-server&#39;)<br>require(&#39;./index.js&#39;)</pre><ul><li>Add serverless.yml</li></ul><pre>service: devops-test-serverless-express<br>provider:<br>  name: aws<br>  runtime: nodejs14.x<br>  region: us-east-2<br>  stage: alpha<br>functions:<br>  proxy:<br>    handler: aws-lambda.proxy<br>    events:<br>      - http:<br>          path: /{proxy+}<br>          method: any<br>      - http:<br>          path: &#39;&#39;<br>          method: any</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*5ICCjYvS_564lnBGZ3TA8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*UAXdfjoSG-N3MXVWg_I1yQ.png" /></figure><ul><li>Test on Local</li></ul><pre>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ZQ3YBzMDwwQBufHgczkKzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*RiyDYYond0fHclsGmdfIXA.png" /></figure><ul><li>Deploy with sls</li></ul><pre>sls deploy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awZCbH3maBEnVCy-oKpY_g.png" /></figure><ul><li>Check Lambda</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5Iitcr5mTgEJAzneowJKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6z5B_Pgo19xiFHAjK1Z2DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*CSJh9WN14JsIBoX29msEWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Ztfb9NHA3TceDz42eFRmVg.png" /></figure><ul><li>If don’t need express. It fine</li></ul><pre>require(&#39;http&#39;).createServer((req, res) =&gt; {<br>  if (req.url === &#39;/ping&#39;) return res.end(&#39;pong&#39;)<br>  if (req.url === &#39;/hello&#39;) return res.end(&#39;world&#39;)<br>  if (req.url === &#39;/&#39;) return res.end(&#39;ok&#39;)<br>})<br>.listen(5000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ShR7qpssgaIE1_GMkx-XZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*IssQbmkVp6yQDSnvU0_ozQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*TxsQvr8fbcM-tTyOYZGH8Q.png" /></figure><ul><li>If we need remove lambda</li></ul><pre>sls remove</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*j3NnqQw9xu2AkDOrTXfXEA.png" /></figure><h3>Troubleshooting</h3><ul><li>When Deploy with “sls deploy” please check about error because I need to add more Priviledge in AWS IAM</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*VUZD1dSdl2E9ViI8DHZO9A.png" /></figure><ul><li>Have fun!!!</li></ul><p>More Ref : <a href="https://www.npmjs.com/package/aws-lambda-http-server">https://www.npmjs.com/package/aws-lambda-http-server</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8727b93c787" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mlflow with Helm and serve Train Model on kubernetes]]></title>
            <link>https://dounpct.medium.com/mlflow-with-helm-and-serve-train-model-on-kubernetes-2d59fec98dd1?source=rss-253b52b8830------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d59fec98dd1</guid>
            <dc:creator><![CDATA[Dounpct]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 17:17:39 GMT</pubDate>
            <atom:updated>2023-08-06T11:38:50.327Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 4: API Transform for Model API</p><p><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-9b6338babc6c">Part 1: Install Mlflow on Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-ae9831982548">Part 2: Train example model and keep in Mlflow Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-671b55fc9780">Part 3: Expose example api on Local Machine</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-2d59fec98dd1">Part 4: API Transform for Model API</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-c835139c4237">Part 5: Install Mlflow on GKE Cluster with helm</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-1d6441277965">Part 6: Keep Model in Mlflow remote Cluster</a><br><a href="https://medium.com/@dounpct/mlflow-with-helm-and-serve-train-model-on-kubernetes-77b4c605a967">Part 7: Serve Model API on Cluster</a></p><p><strong>API Transform</strong></p><p>From Part 3 if api server must handle request that user must call like this</p><pre>curl -X POST -H &quot;Content-Type:application/json&quot;                     \<br>    --data &quot;{\&quot;dataframe_split\&quot;: {\&quot;data\&quot;:[[                          \<br>        0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  <br>        0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  <br>        0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,<br>        0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  <br>        0.0,  0.0,  1.0,  0.0]]}}&quot;                                      \<br>    http://127.0.0.1:1234/invocations</pre><p>It not easy. Because user never know what is 0.0 …. mean and order. So user need to call like this</p><pre>curl -X POST -H &quot;Content-Type:application/json&quot;                     \<br>    --data &#39;{&quot;country&quot;: &quot;Russian Federation&quot;,&quot;timestamp&quot;: &quot;Feb 22, 2023 @ 16:59:59.942&quot;}&#39;  \<br>    http://127.0.0.1:6789/v2/gateway</pre><p>It easier right!!!.</p><p><strong>Create Gateway Server API</strong></p><ul><li>Create new server.py in some project with train.py and import lib. Actually we should separate file to another project for deploy to another microservices on cluster.</li></ul><pre>from flask import Flask, request, jsonify<br>import requests<br>import json<br>from waitress import serve<br>import os<br><br>import pandas as pd<br>from sklearn.compose import make_column_transformer<br>from sklearn.preprocessing import OneHotEncoder<br>from sharelib import maskOfficeHour</pre><ul><li>Add default env that can change when deploy in cluster with Deployment</li></ul><pre>app = Flask(__name__)<br>host = os.environ.get(&#39;host_ml&#39;, &#39;127.0.0.1&#39;)<br>port = os.environ.get(&#39;port_ml&#39;, &#39;1234&#39;)<br>gateway_port = os.environ.get(&#39;gateway_port_ml&#39;, &#39;6789&#39;)</pre><ul><li>Create function for transform user data</li></ul><pre>def createDataV2(request_country,request_timestamp):<br><br>    print(request_country + &quot; &quot; + request_timestamp)<br>    <br>    test_df = pd.DataFrame([[request_country,request_timestamp]],columns=[&#39;mt.ads_country_dst&#39;, &#39;@timestamp&#39;])<br>    test_df = maskOfficeHour(test_df)<br>    test_df = test_df.drop([&#39;@timestamp&#39;], axis=1)<br><br>    X_new = X_transform.transform(test_df)<br>    <br>    data = {<br>        &quot;data&quot;:<br>        X_new.toarray().tolist()<br>    }<br><br>    return data</pre><ul><li>Create API path that will convert data and send to invocations</li></ul><pre>@app.route(&#39;/v2/gateway&#39;, methods=[&#39;POST&#39;])<br>def get_invocationsV2():<br>    headers = {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    }<br><br>    content = request.json<br>    request_country = content[&#39;country&#39;]<br>    request_timestamp = content[&#39;timestamp&#39;]<br>    content_data = createDataV2(request_country,request_timestamp)<br><br>    try:<br>        resp = requests.post(<br>            url=&quot;http://%s:%s/invocations&quot; % (host, port),<br>            data=json.dumps({&quot;dataframe_split&quot;: content_data}),<br>            headers=headers,<br>        )<br><br>        print(resp.status_code)<br>        return resp.json()<br><br>    except Exception as e:<br>        errmsg = &quot;Caught exception attempting to call model endpoint: %s&quot; % e<br>        print(errmsg, end=&quot;&quot;)<br>        return resp.json()</pre><ul><li>Create main that load Dataset and create column_transformer pattern</li></ul><blockquote><strong>This is so importance for use same dataset to create column_transformer to fit dataframe when training model and when convert data in api transform</strong></blockquote><pre>if __name__ == &#39;__main__&#39;:<br>    df = pd.read_csv(&quot;data/firewall-traffic.csv&quot;)<br>    df_country = df[&quot;mt.ads_country_dst&quot;]<br>    df_OfficeHour = maskOfficeHour(df)<br>    df_categories = pd.concat([df_country, df_OfficeHour[&#39;is_OfficeHour&#39;]], axis=1, sort=False,)<br>    enc = OneHotEncoder(handle_unknown=&#39;ignore&#39;)<br>    X_transform = make_column_transformer((enc,[&#39;mt.ads_country_dst&#39;]),(enc,[&#39;is_OfficeHour&#39;]))<br>    X_transform.fit(df_categories)<br>    <br>    print(&quot;Server Ready On Port &quot; + gateway_port)<br><br>    serve(app, host=&quot;0.0.0.0&quot;, port=gateway_port)</pre><p><strong>Test API Transform</strong></p><ul><li>Start Server.py</li></ul><pre>python server.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wOoy-nyirsoxu4a2jypWw.png" /></figure><ul><li>Test call</li></ul><pre>curl -X POST -H &quot;Content-Type:application/json&quot;                     \<br>    --data &#39;{&quot;country&quot;: &quot;Russian Federation&quot;,&quot;timestamp&quot;: &quot;Feb 22, 2023 @ 16:59:59.942&quot;}&#39;  \<br>    http://127.0.0.1:6789/v2/gateway | jq</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1Y0kiV0fzG4TgTs5Ov_CQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*cfSL0D-ugrjTCmGZyyRApQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0mGHUklb9KW0qmaaMGyUg.png" /></figure><ul><li>Let try more for more traffic</li></ul><pre>while true;do curl -X POST -H &quot;Content-Type:application/json&quot;                     \<br>    --data &#39;{&quot;country&quot;: &quot;Russian Federation&quot;,&quot;timestamp&quot;: &quot;Feb 22, 2023 @ 16:59:59.942&quot;}&#39;  \<br>    http://127.0.0.1:6789/v2/gateway;done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKHDAI6HqL4TfDFUGmlFBA.png" /></figure><ul><li>Have fun!!!</li></ul><p>Note for my idea this API Transform must serve near real time traffice from another system. So it need cache system.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Credit : TrueDigitalGroup</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d59fec98dd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>