Lange: The secret maze of Debian images

Post Syndicated from jzb original https://lwn.net/Articles/1010855/

Debian Developer Thomas Lange has written a blog post
in the attempt to help users find the right Debian image for their
systems.

It’s difficult to find the right Debian image. We have thousands of
ISO files and cloud images and we support multiple CPU architectures
and several download methods. The directory structure of our main
image server is like a maze, and our web pages for downloading are
also confusing.

Security updates for Wednesday

Post Syndicated from jzb original https://lwn.net/Articles/1010853/

Security updates have been issued by AlmaLinux (gcc-toolset-14-gcc, nodejs:18, and nodejs:22), Fedora (bootc), Gentoo (OpenSSH), Oracle (doxygen, libxml2, mingw-glib2, and NetworkManager), Red Hat (bind, bind9.16, bind9.18, kernel, kernel-rt, mysql, and mysql:8.0), Slackware (openssh), SUSE (buildah, emacs, glibc, google-osconfig-agent, grub2, java-11-openj9, kernel, netty, netty-tcnative, openssh, openvswitch, podman, and ucode-intel), and Ubuntu (atril, libsndfile, libtasn1-6, openssh, python-virtualenv, and symfony).

Rapid7 Fills Gaps in the CVE Assessment Process with AI-Generated Vulnerability Scoring in Exposure Command

Post Syndicated from Rapid7 original https://blog.rapid7.com/2025/02/19/rapid7-fills-gaps-in-the-cve-assessment-process-with-ai-generated-vulnerability-scoring-in-exposure-command/

Rapid7 Fills Gaps in the CVE Assessment Process with AI-Generated Vulnerability Scoring in Exposure Command

The National Vulnerability Database (NVD) announced in February 2024 that it would no longer provide common vulnerability scoring system (CVSS) scores for all CVEs. Due to resource constraints and an inability to keep up with the volume of newly-disclosed vulnerabilities, NVD shifted its focus to processing vulnerabilities more efficiently by relying on vendor-provided and third-party scores rather than scoring each CVE independently.

Many organizations rely on NVD’s CVSS scores as a consistent, centralized guide to measuring the potential risk of vulnerabilities. This is especially useful for teams that don’t have the resources to conduct their own in-depth vulnerability analysis given the pace at which new CVEs are cropping up.

To address this widening gap in vulnerability scoring and ensure our customers are making informed decisions with the most accurate understanding of their current risk posture we’re excited to announce the release of AI-Generated Risk Scoring in Exposure Command. By integrating an advanced machine learning model, Exposure Command supplements existing CVSS scores by providing AI-Generated Risk Scores for CVEs where NVD does not provide them, ensuring all vulnerabilities are provided an accurate score.

The need to evolve from traditional vulnerability management practices to continuous threat and Exposure Management

Moving beyond simple risk scoring methodologies is critical for modern vulnerability management teams to stay ahead of advanced threats. For many organizations, this means adopting a Risk-Based Vulnerability Management (RBVM) approach.

Put simply, this means incorporating not just a deep and accurate understanding of how risky a given CVE is in a vacuum, but also layering on additional context related to reachability and exploitability, asset criticality, and a real-world understanding of what threat actors are actively targeting in the wild. And how all these inputs relate to the organization’s specific environment.

AI-Generated CVSS scoring in Exposure Command feeds directly into our broader Active Risk scoring methodology. More importantly, it empowers Rapid7 to produce predictive CVSS scores by analyzing vulnerability information and comparing with previous expert vulnerability analysis.

The model generates each vector individually, and once combined to form a score, results in 76% of these generated scores being in the correct severity classification. Combined with Rapid7’s Active Risk calculator, this increases to 87% of scores returning the correct classification. The remaining scores are never more than one classification out.

This insight will feed directly into and improve the overall accuracy of our Active Risk scoring models, as well as, ensure severity scores are assigned and provided to security teams faster than humanly possible, making your entire security program more resilient to external change.

By leveraging AI/ML to generate predictive risk scores, security teams benefit from:

  • Enhanced accuracy: Our expertly designed model trained on historical NVD data accurately provides CVSS scores.
  • Predictive scoring: Get immediate insight into the severity of newly-disclosed CVEs that are left unscored, without the need for manual aggregation and analysis.
  • Improved security posture: Ensuring all CVEs are assigned an accurate severity score, organizations are equipped with the necessary context to effectively prioritize remediation efforts and in turn strengthen their organization’s security posture.

This release represents a major step forward in our mission to provide industry-leading cybersecurity solutions. We expect these enhancements will significantly improve your ability to assess and manage vulnerabilities, giving you the confidence to stay ahead of potential threats.For more detailed information and implementation guidelines, please refer to the release notes. If you’d like to learn more about the Rapid7 AI Engine and how we’re leveraging AI across the platform, download the eBook today!

Истории на върха на налъма (продължение)

Post Syndicated from Атанас Шиников original https://www.toest.bg/istorii-na-vurha-na-naluma-produljenie/

<< Към първа част

Истории на върха на налъма (продължение)

Според преданията (хадиси) Пророкът, докато водел молитвата на общността, свалял сандалите си и ги полагал от лявата си страна. Като видели това, неговите последователи започнали да правят същото. Нормално, бих добавил аз. Когато си убеден, че това е „Пратеникът на Аллах“ (Расул Аллах) и че той е „прекрасен образец“ за теб (Коран 33:21), ще искаш да си като него. След края на молитвата Пророкът запитал хората защо го правят, а те отвърнали, че е, защото са го видели да постъпва по този начин. Той пък разказал как самият архангел Джибрил (библ. Гавраил) го е осведомил, че върху сандалите му има мръсотия. Оттук и заръката към мюсюлманите – видят ли, че сандалите им са зацапани, на път за джамията, да ги избършат и тогава да се молят. 

По време на един от военните походи (газуа) Пророкът казал на правоверните да гледат да носят сандали, защото човек остава яздещ, докато е обут със сандали. А ако връвта на единия сандал се скъса, да не се ходи с един сандал. Тогава е по-добре бос. В друг пък разказ един от съратниците извадил два сандала (или налъма?) с каишки, за които друг казал: „Това бяха сандалите на Пророка.“ Било предадено, че Мохамед веднъж наложил наказанието за пиене на вино чрез бой с палмови клони и сандали. Или налъми. А Абу Бакр по този повод отмерил четирийсет удара. В друга версия на същия разказ самият Пророк налагал по четирийсет удара с палмови клонки или сандали. Налъмът, съответно сандалът, може да служи и като знак за състояние на посвещаване и ритуална чистота при поклонението хадж, наричано ихрам. Съпровожда се с обличане на определени дрехи. А Мохамед препоръчва тогава да се носят сандали. Не може затворени обувки. Извън специфичната регулация на поклонението, Пратеникът на Аллах според едно предание забранил човек да си нахлузва чепика, докато е изправен. 

Без да превръщаме този текст в енциклопедия на налъма по шериата, става ясно, че

назидателната употреба на чепика съвсем легитимно може да бъде подплатена с религиозен аргумент.

Очевидно е възможно да имаме едно и също следствие, породено от различни причини. Идейните основания на баба ми едва ли са свързани със Сунната. Както и Вазовото „биене по ръцете“, „задницата на престъпника“, че и на страховитата „фалага“ – с бой по ходилата. Но в рамките на една добре информирана от Корана и Сунната образователна и възпитателна традиция може да очакваме причинно-следствена връзка между тях и препоръките да се възпитава чрез бой, нали? А в старите медресета това е неизменна част от образованието. Така поне научавам от арабски образователни класики, като съчиненията на Ибн Сахнун от IX век или Ал-Кабиси от следващото столетие и началото на XI век.

На учениците се нанасят до десет удара, като причините са много – лентяйство, бавно запомняне на текста на Корана, грознопис, заспиване по време на урок.

Съветът е да се избягват чувствителни части, например лицето, да се внимава да не се нанесе трайна телесна повреда, но да се причини болка. Лошият учител се отличава с това, че наказва учениците заради своя собствен гняв, а не „заради тяхна полза“. Препоръчват се удари по нозете, защото, по думите на Ал-Кабиси, те „са най-издръжливи на болка“ и рискът да се стигне до голямо увреждане е нисък. А от други извори знаем, че наказанието се нанася чрез пръчка, с дреха или със сандал, налъм, чехъл, както искате го наречете. 

Възпитателната мярка според традиционното арабско право обаче не е приравнена с наказанието, наложено за простъпки на свещения закон. Има различни термини. Възпитателното наказание чрез бой обикновено се обозначава с та’диб, тоест „дисциплиниране“. Идва от арабската дума адаб, тоест „етика“, „възпитание“, „порядки“, но също и „литература“. Оттам пък изразът байт ал-адаб, тоест „дом на етикета“, на „добрите порядки“ или направо „домът на литературата“, е един от много евфемизми за тоалетна. За боя с цел наказание по свещения закон се употребяват други термини. Но и при него сандалът играе роля. И до днес е така, както свидетелстват запитвания на мюсюлмани из големите портали за онлайн запитвания (фетви) относно наказанията чрез бой с палмови пръчки или сандали, налъми, обувки… 

Освен към инструменталната и негативно натоварена наказателна употреба на налъма, текстовете на Корана и Сунната отпращат и към други културни практики, например съногаданието.

Големите арабски съновници, включително и този на Ибн Сирин от VII век, комуто се приписва първият запазен сборник с мюсюлмански тълкувания на сънищата, твърдят, че ако сънуваш да те бият с налъм или сандал, ще бъдеш изложен на упреци.

Само че сандалът на Пророка е друго нещо. Около него се развива специфична литература, посветена на достойнствата му. Разказва се, че векове след смъртта на Пророка все още съществуват автентични съхранени негови сандали. Един от тях е предаден от съпругата му Аиша. Парче от сандал на Мохамед се открива запазено и в Кайро през IX век при съдията Абд ал-Басит ибн Халил ибн Ибрахим от Дамаск. Имало и друг запазен образец в училището по хадис „Ал-Ашрафия“ в Дамаск, също историците говорели за още един, запазен в мароканския град Фес по времето на прочутия Мулай Исмаил ибн Шариф, султан на Мароко в края на XVII и началото на XVIII век. Така поне твърди богословът Ахмад Таймур от Египет, когато пише „Реликвите на Пророка“ в средата на миналото столетие и обговаря наличните артефакти, приписвани на Мохамед. Да речем, плащ, меч, косми, знаме. И разбира се – дълго разсъждение, посветено на свидетелствата за запазен „пророчески свети сандал“ (ан-на‘л аш-шарифа ан-набауийа). 

А Фес не е случайно място, особено що се отнася до свети налъми и сандали.

Там се подвизава авторът на най-известното съчинение за сандалите, или налъмите на Пророка. Ахмад ибн Мухаммад ал-Макарри живее през втората половина на XVI и първата половина на XVII век и произхожда от Тлемсен в Алжир. Кариерата му на богослов и правист го отвежда във Фес и Маракеш като част от дворцовото обкръжение на Ахмад ал-Мансур, мароканския султан от края на XVII столетие. След като Ал-Мансур умира през 1603 г., Ал-Макарри се установява отново във Фес и поема престижния пост на имам на джамията „Ал-Карауин“, към която от IX век действа и едно от най-авторитетните религиозни училища в мюсюлманската история. Чак години по-късно, през 1617-та, заминава за Кайро. Там започва да пише най-известното си съчинение – история на мюсюлманска Испания (Ал-Андалус), която се превръща в стандартен справочник по темата на Запад поне до ХIХ столетие. Пътува до Дамаск, Мека, Медина, преподава хадис и умира през 1632 г., докато се подготвя да се установи в Дамаск. Изобщо, мюсюлманските богослови и прависти са космополитни. Пътешестват много по работа, за препитание, по лични причини, в преследване на политическа кариера или пък в заръчаното още от Пророка „търсене на религиозно знание“ (талаб ал-‘илм). 

Но за нас е интересно друго. През 1621 г. Ал-Макарри пише съчинение, посветено на обущата на Пророка. А заглавието на арабски е впечатляващо и римувано, както му се полага – „Победа от Всевишния в прослава на сандалите“ (Фатх ал-Мута‘али фи мадх ан-ни‘али). Може да си поиграем с превода – арабските заглавия на съчинения го заслужават. Често пъти са дълги, метафорични, конструирани са от формални, да не река изкуствени рими. Бих могъл да предложа и „Завоевание от Всевишния във възхвала на налъмите“. И тези два варианта далеч не изчерпват всички възможности. А съчинението се е превърнало в класика. Започва с разглеждане на частите от Сунната, посветени на сандалите на Пророка. Обсъждат се и значения на точно определени изрази от тях, тълкувания на богослови, живели преди. Ако искате да се гмурнете в темата и сте готови да се вкопчите в борба с арабския език от XVII век, това е вашето четиво в чудесен, чист и четивен препис, съхраняван понастоящем в библиотеката „Честър Бийти“ в Дъблин. 

За по-визуално ориентираните читатели документът съдържа безценни изображения. Ето как в епохата на Ал-Макарри изглеждат различните видове сандали.

Запомнете този дизайн. Хем са много сходни, хем различни. Разширена основа, стесняване в долната част, нагоре заоблено разширяване и заострен връх. 

А защо е важна формата? Защото точно в тази форма исторически се появяват и талисманите на „светия сандал“, да не кажа „налъм“ (като един поп Минчо Кънчев). И до днес може да си купите такъв. Християните носят кръстчета, евреите имат своите „Маген Давид“ („щитът на Давид“, известен още като „звезда“), а мюсюлманите носят талисмани с формата на сандалчета от метал или дърво. Често пъти не са празни по средата като тези на Ал-Макарри, а са запълнени с геометрична орнаментация или са изписани с благочестиви формули. Може да си ги сложите в рамка на стената, на ключодържатели, като висулка или като декорация на дрехата. На късмет било, твърди се в мюсюлманските общности онлайн, където богослови много често обясняват какви са достойнствата на сандалите на Пророка, и препращат към предходни съчинения по въпроса. Дори материалът на оригиналните сандали на Мохамед е предмет на обсъждане. Жълти били, от кравешка кожа. 

За това жълто се сещам, докато се разхождам из пазара във Фес по време на пътешествието ми там. Кожените сандали и чехлите греят в пъстри, ярки цветове. „Как ги наричате тези?“, питам един продавач. Книжовният ми арабски винаги предизвиква шок. Човекът явно държи малък дюкян за портмонета, обувки, сандали, чехли и след първоначалния стрес от моя арабски превключва на много сносна версия на езика на Пророка. „Тук им казваме бабуш“, ми обяснява. А, ясно. Думата, подозирам, е свързана с нашенската папук, която шества из Персия, Турция, Близкия изток, та чак до Мароко. Като четеш обяснения за бабуш по арабските сайтове, често пъти го представят като вид на‘л. Само че не е толкова отворен, прилича на чехъл със заострен връх, не толкова на налъм или на сандал. Тъй като Фес е мястото и на известните бояджийници за кожа, където недейте стъпва, ако сте с чувствителен нос, питам и за вида кожа. „Имаме четири вида – най-скъпата е камилската, после е кравешката, после овчата и накрая – тази от коза“, ми се казва. А дали е така, не знам, приемам го на доверие. „Добре, а защо някои кожени неща, които искаш да ми продадеш, са овехтели и позагубили баграта си?“ – продължавам да разпитвам. „Защото са боядисани с естествено багрило, което е щадящо природата.“ Разсмивам се. Веднага се сещам за диалога ми с продавач на сувенири на Капалъчаршъ в Истанбул преди много години. 

– Колко искаш за тези сувенирни украси от керамика? – питам един продавач.
– 40 долара! – отговаря.
– Добре – казвам, – за тези пари ще взема две, плюс ей тази декоративна метална кутийка. 
– А, не! – обижда се. – Само тази кутийка струва петдесет долара. Погледни я, от сребро е, а вътре е слонова кост.
– Виж сега. Това не знам дали е сребро, но вътре виждам само пластмаса.
– Е – казва той веднага, без дори да се замисли, – така е. Ама не ръждясва!
– Браво! – разсмивам се аз. – Не ги искам.

С това пътешествието на върха на налъма приключва. Но остава с отворен край. Започнало от „шамарената фабрика“ на социализма с налъмен привкус, преминаващо през възрожденската дряновица и бунтовните ни свещеници, Корана, Сунната, султани, принцове и везири в халифата. Всички те мързеливо се пошляйват по ориенталски сандали някъде в сокаците между пазари, хамами, палати, дюкяни, медресета и джамии, между България, арабския свят, Османската империя и Северна Африка. И ако някой ми каже, че темата е изчерпана, бих му отвърнал, че това ще стане, ама когато цъфне налъмът.


В рубриката „Ориент кафе“ Атанас Шиников поднася любопитни теми, свързани не толкова с горещата политика, колкото с историята и културата на Близкия изток. А той, древен и днешен, е по-близко до нас и съвремието ни, отколкото си представяме.

Code Club: Empowering the Next Generation of Digital Creators

Post Syndicated from Sophie Ashford original https://www.raspberrypi.org/blog/code-club-empowering-the-next-generation-of-digital-creators/

Code Club is more than just a place to learn coding — it’s a thriving global community where young minds discover, create, and grow with technology. With a refreshed look and ambitious goals for 2025, Code Club is set to connect an even larger network of mentors and reach millions more young people worldwide.

Code Club at RPF HQ, Cambridge
Code Club at RPF HQ, Cambridge

Since it was founded in the UK in 2012, Code Club has grown into a global movement, inspiring over two million young people to build apps, games, animations, websites, and more. Supported by the Raspberry Pi Foundation, Code Club provides free training and resources to mentors, ensuring creators achieve meaningful and lasting skills. Our vision for the next decade? To empower ten million more young people to have confidence in their coding.

A proven impact

A recent independent evaluation by the Durham University Evidence Centre for Education (DECE) confirmed what we’ve always believed: Code Club makes a real difference. Young people who attend gain valuable coding skills, grow in confidence, develop a strong interest in technology, and find a sense of belonging in the digital world.

Mentor Rajan at his Code Club in India
Mentor Rajan at his Code Club in India

The power of mentorship

At the heart of Code Club are passionate volunteers who bring coding to life. Whether it’s the thrill of overcoming a challenge or the excitement of seeing an idea come to life on screen, mentors make a lasting impact while learning coding skills alongside their club’s creators.

Bob Bilsland, a dedicated volunteer since 2012, runs one of the world’s longest-running Code Clubs at Malvern CofE Primary School, Worcestershire, England. His motivation?

“What brings me back week after week is the sharing of what I enjoy doing. It’s so much fun to help others explore this space themselves, to see what they can personally create. I see that giving others the opportunity to explore and familiarise themselves with computing as something that could open up a world of possibilities for them in the future.” 

For Yang, a mentor at the EY office clubs, representation in tech is key:

“If there are some female role models, I think for a little girl growing up, that means so much. Because if they can see somebody thrive in this industry, they will see themselves there one day. And that’s the inspiration.” 

Mentor Yang at her Code Club in London
Mentor Yang at her Code Club in London

Across the world, volunteers like Nadia in Iraq and Solomon in The Gambia are using Code Club to bridge the digital divide, create opportunities, and empower communities.

“[Code Club] added to my skills. And at the same time, I was able to share my expertise with the young children and to learn from them as well.” – Nadia Al-Aboody, Iraq.

“We strongly believe in the transformative power of digital skills and their potential to create opportunities for young people. Witnessing the lack of access to computer knowledge among high school graduates in The Gambia and other sub-Saharan African countries inspired us to take action. By bridging the digital skills gap, we aim to empower young individuals to thrive in the 21st century.” – Solomon, Gambia 

A community that inspires

Code Club isn’t just loved by mentors; it’s so important to the young people who participate.

Eoghan, a young creator from Ireland, values the collaboration and support he receives:

“It’s really fun to meet and talk about ideas with other creators, and the mentors are very helpful in fixing any coding problems.” 

Mentor Jayantika at her Code Club in Pune, India
Mentor Jayantika at her Code Club in Pune, India

Jayantika, a 15-year-old from rural Pune, India, started as a creator and is now a peer mentor. For her, Code Club is about giving back:

“I believe coding opens doors and helps young children express their creativity. By mentoring, I hope to prepare them for a future that is increasingly driven by AI and technology.” 

Join the movement

Along with the incredible community, Code Club is supported by sponsors and funders who share our mission. We would like to extend a thank you to Cognizant, who have committed their support to the Code Club mission in the UK and Ireland for 2025.

Mentors gathering at Clubs Con 2024
Mentors gathering at Clubs Con 2024

Code Club is more than just learning to code; it’s about creating opportunities, encouraging confidence, and building a global network of digital creators. Whether you’re a mentor, educator, or young digital maker, there’s a place for you in our community. Start your Code Club journey today and join a global community of digital creators.

The post Code Club: Empowering the Next Generation of Digital Creators appeared first on Raspberry Pi Foundation.

Корейският полуостров в геополитическата игра на калмари

Post Syndicated from Искрен Иванов original https://www.toest.bg/koreiskiyat-poluostrov-v-geopoliticheskata-igra-na-kalmari/

Корейският полуостров в геополитическата игра на калмари

Корейският конфликт е най-голямото доказателство, че когато в даден регион не съществува единен център на сигурност, конфликтите, наследени от Втората световна война, може да надживеят дори разпадането на двуполюсния модел САЩ–СССР. Целта на този материал ще бъде да изясним някои ключови геополитически детайли, свързани с региона на Източна Азия, който е сочен като една от най-горещите точки на нестабилност в системата на международните отношения днес. Уникалното в корейския конфликт е, че той е най-старият от новото поколение конфликти, като същевременно неговото разрешаване се счита от младите хора в Република Корея за „мисия невъзможна“.

Наричаме го конфликт, защото съгласно международното право той отговаря напълно на тази дефиниция: между двете Кореи не съществува мирен договор, а замразено противопоставяне и то – предвид интересните времена, в които живеем – може лесно да се размрази. Но наистина ли не съществува никакъв сценарий, при който Корейският полуостров най-сетне да възкръсне единен от прахта на десетилетното противопоставяне между Сеул и Пхенян? Кой всъщност е гарант за сигурността на този регион и дали гаранциите, дадени от САЩ на Република Корея, все още отговарят на геополитическите реалности предвид осезаемото сближаване между Корейската народнодемократична република и Русия? И не на последно място, защо е толкова трудно народите от двете страни на 38-мия паралел да съжителстват в рамките на една политическа система? 

След като отговорим на тези въпроси ще видим, че корейският конфликт на практика е една геополитическа игра на калмари, чийто сценарий е подобен на популярния южнокорейски сериал и елегантно загатва кои са истинските фактори зад непримиримите отношения между Северна и Южна Корея.

Корейският полуостров в геополитическата игра на калмари
Сателитна снимка на Северна и Южна Корея през нощта. Снимка: Wikimedia Commons / NASA

Какво представлява корейският конфликт?

Научните дефиниции как трябва да възприемаме конфликта между двете Кореи са много, но емпирично най-издържаната от тях принадлежи на структурния реализъм. Част от бащите основатели на американската геополитическа школа, като Робърт Джървис и Ричард Бетс, приемат, че за разлика от Студената война, която е по-скоро сблъсък на две социални системи, корейският конфликт е класически пример за дилема на сигурността.

В този дух са и изследванията на корейски политолози като Ким Йонго и Ким Джонгсоп, склонни да търсят причините за противопоставянето между Сеул и Пхенян в постоянната надпревара във въоръжаването. Оттук може да се разбере защо този конфликт все още тлее – дилемите на сигурността продължават да функционират дотогава, докато една от двете страни не преустанови съществуването си. Или по-просто казано, двете Кореи се намират в състояние, при което всяко повишаване в сигурността на едната страна провокира реакция от другата. И единственият гарант, че уравнението няма да излезе извън контрол, остават геополитически актьори като САЩ и Китай, които възпират партньорите си от ескалация. До този момент.

Два са основните фактори, които засега правят мирното разрешаване на корейския конфликт геополитическа илюзия: севернокорейската ядрена програма, която продължава да се развива в разрез с ангажиментите, поети от Пхенян към Москва по време на Студената война, и сближаването между Русия и Северна Корея. Последното всъщност е най-голямото доказателство, че съветската политика е била далеч по-прагматична от тази на сегашната администрация в Кремъл, която – след подписването на Договора за стратегическо партньорство между КНДР и Руската федерация – на практика дава зелена светлина на севернокорейския лидер Ким Чен Ун да увеличи ядрения си арсенал. По този начин Северна Корея най-сетне става част от двустранен формат, който може да гарантира нейната сигурност – ако разбира се, приемем, че гаранциите, предоставени ѝ от Москва, са надеждни.

Корейският полуостров в геополитическата игра на калмари
Владимир Путин и Ким Чен Ун по време на приятелската визита на руския президент в Пхенян, юни 2024 г. Снимка: Wikimedia Commons / Kremlin.ru

Но наистина ли сближаването между Москва и Пхенян е в състояние да изравни баланса на силите на Корейския полуостров? Отговорът на този въпрос не е еднозначен и зависи от два фактора.

Първият ключов фактор е функционирането на Договора за взаимна защита между САЩ и Република Корея, който е и основният гарант на съюзните договорености между Вашингтон и Сеул. Член 3 от този договор задължава двете правителства да се консултират в случай на обща заплаха за сигурността им. Член 4 дава право на САЩ да поддържат военно присъствие на територията на Южна Корея, каквото има и до ден днешен.

До този момент нито един американски или корейски президент не си е позволявал да постави под въпрос съюзните договорености между двете страни. Малко вероятно е Доналд Тръмп да го направи, тъй като, както вече стана ясно, сдържането на Китай остава главен приоритет за неговата администрация. Наред с това следва да признаем тъжния факт, че сам по себе си този Договор вече е изчерпан и не дава достатъчни гаранции за сигурността на двете държави, тъй като Пхенян разполага с ядрено оръжие, което обезсмисля конвенционалните механизми за сдържане, прилагани от САЩ в продължения на десетилетия.

Вторият ключов фактор е Вашингтонската декларация от 2023 г., подписана от президента на САЩ Джо Байдън и президента на Южна Корея Йон Сук Йол. Тя поставя началото на нова поредица от американски ангажименти към Сеул. Включена е и клауза, съгласно която САЩ си запазват правото да употребят ядрено оръжие, в случай че Южна Корея бъде нападната. Тъй като Америка не е декларирала в своята ядрена доктрина отказ от едностранна употреба на оръжия за масово унищожение, такъв сценарий е възможен срещу всеки противник, защото този документ не уточнява дали ангажиментът се отнася само при атака от страна на Пхенян.

Корейският полуостров в геополитическата игра на калмари
Южнокорейският президент Йон Сук Йол, бившият американски президент Джо Байдън и японския министър-председателят Шигеру Ишиба на тристранна среща в Япония, ноември 2024 г. Снимка: Wikimedia Commons / Японско правителство

С администрацията на Тръмп начело на САЩ обаче, бъдещето на Вашингтонската декларация е съмнително. След неуспешния опит на Йон Сук Йол да въведе военно положение в страна, от друга страна, е възможно прокитайската фракция в южнокорейския парламент да засили позициите си, което допълнително може да обтегне отношенията между Сеул и Вашингтон. Към това се прибавят и опитите на Тръмп да постигне споразумение с Путин за край на войната в Украйна, което определено ще повлияе и на отношенията между САЩ и Северна Корея.

Ролята на Китай – от гарант към почетен зрител

Китай винаги е имал особено отношение към Корейския полуостров, защото поделянето му е от стратегическо значение за Пекин. Докато режимът на Ким Чен Ун все още е на власт, Китай разполага с огромен буфер, който не би позволил на САЩ да разположат свои оръжия на китайската граница. Същевременно Северна Корея е единствената държава, с която китайците имат съюзен договор – Договора за приятелство, сътрудничество и взаимопомощ между КНР и КНДР. Член 2 от това споразумение задължава двете страни да се противопоставят заедно на всяка коалиция от държави, която може да представлява заплаха за сигурността им.

Въпреки надеждата на администрацията на Байдън, че договорът няма да бъде подновен поради сближаването на Пхенян с Москва, китайското ръководство препотвърди ангажиментите си към Северна Корея през 2021 г., тъй като счете, че това е единственият начин да гарантира твърдо сигурността на границите си в контекста на геополитическото противопоставяне със САЩ. Нямаме основание да се съмняваме, че севернокорейският ангажимент към Китай има същата тежест – за затворената държава всеки съюзник е добре дошъл, особено ако е втората най-голяма икономика в света.

Корейският полуостров в геополитическата игра на калмари
Китай и Северна Корея празнуват дружбата си с масови игри, септември 2010 г. Снимка: Wikimedia Commons / Roman Harak

Южнокорейската политика към Китай е комплексна, но единна във всяко отношение. Това е плод не само на дългосрочните икономически интереси, които има Сеул, но и на т.нар. концепция за азиатската йерархия, която всички държави от Източна и Южна Азия с изключение на Индия спазват. Съгласно тази доктрина, въпреки историческите реалности, превърнали Китай от империя в народна република, на Пекин се отдава почетно уважение като на културата извор, от която останалите източноазиатски народи са получили своето просветление. По тази причина, въпреки огромните си политически различия и разнородните си съюзници, азиатските държави винаги са се отнасяли към Китай като към „първородния“, с който не могат да скъсат нито икономическите си, нито културните си връзки. 

Либералите в Южна Корея винаги са били по-големи синофили от ястребите консерватори, но последните рядко са си позволявали напрежение в отношенията с Пекин въпреки политиката им за сближаване с Япония. Затова и Китай остава скритата надежда за много южнокорейци, които се надяват, че дори политик като Си Дзинпин няма да допусне Северът да доведе Корейския полуостров до състояние на ядрена ескалация. Китай знае това и не се тревожи за отношенията си със Сеул. Остава отворен въпросът дали Америка е наясно с тези културни специфики и по какъв начин може да ги компенсира.

Тъжната реалност за Китай е, че ако не успее да удържи сближаването между Москва и Пхенян, твърде е възможно в един момент то да се обърне срещу него. Причината е, че инстинктите на ядрените държави често могат да станат жертва на лидерското его, което управлява политическите им системи. Войната в Украйна показа, че Русия умее да блъфира с ядрената си доктрина и че има ясно очертани червени линии, отвъд които ескалацията пак е вероятен, но не задължителен сценарий заради чувството за самосъхранение, което има руското ръководство. 

Корейският полуостров в геополитическата игра на калмари
Ким Чен Ун се прегръща на раздяла с бившия южнокорейски президент Мун Дже Ин по време на посещението на Доналд Тръмп през първия му президентски мандат на демилитаризираната зона между Северна и Южна Корея, юни 2019 г. Официална снимка на Белия дом от Shealah Craighead

Но Северна Корея няма червени линии просто защото за нейния лидер личното му политическо оцеляване стои дори над това на народа му и държавата – визия, която напълно е погълнала чувството му за самосъхранение. Обкръжението му не би могло да извърши преврат, защото репресивният апарат на КНДР е изключително добре развит и функционира така, че и най-добрите съветски агенти биха могли да му завидят. Русия разбира добре цената на приятелството без граници с Китай, а Пекин има усет докъде би могъл да оказва натиск върху Путин. Но лидер като Ким Чен Ун е напълно непредсказуем и в един конфликт със САЩ Китай едва ли би могъл да го убеди да не натиска червеното копче. Най-малкото защото Пхенян вижда в ядрения си пакт с Москва много по-големи гаранции за сигурност, отколкото в споменатия по-горе член 2 в договора с Пекин.

Възможно ли е Корея да се обедини отново?

Тези, които познават корейците, веднага ще отбележат, че този въпрос е неправилно зададен. По-правилно би било да се запитаме желаят ли го корейците. 

Жители на Севера, разбира се, не биха могли да дадат обективен отговор на този въпрос, но повечето бегълци от режима на Ким споделят, че репресиите дотолкова са промили съзнанието на севернокорейците, че те виждат Юга като свой вечен враг. За старото поколение южнокорейци, обединението – или т.нар. слънчева политика – е жизненоважен приоритет, който произлиза от тяхното минало и от носталгията им по загубеното единство. Много от по-възрастните южнокорейци признават, че обединението със Севера е необходимо и че режимът на Ким, а не неговите поданици, е виновен за сегашното статукво. Някои дори напускат Южна Корея на преклонна възраст и бягат на север, защото искат да завършат живота си по местата, където са родени. 

Младото поколение на кей-поп и Squid Game, уви, възприема Северна Корея като ненужна финансова тежест, която ще се стовари като чук върху южнокорейската икономика и ще намали драстично жизнения стандарт в страната. За тях сближаването с Ким и връщането към корейските традиции е отдавна изгубена кауза от миналото, която може да коства на Южна Корея нейната независимост, извоювана от героите на Корейската война. Севернокорейците пък са възприемани като commies, които служат на един луд диктатор, способен да заличи с оръжията си Сеул от картата.

Но безспорно най-големите пречки пред обединението на Корейския полуостров остават ядрените оръжия. Политическа фикция е да смятаме, че траен мир може да има, докато Ким Чен Ун държи в ръцете си малък, но функционален ядрен арсенал, чиито ракети могат да достигнат територията на САЩ. 

Южнокорейското общество е силно разделено по този въпрос, защото все по-голяма част от корейците смятат, че страната има нужда от ядрено оръжие, за да сдържа Пхенян. Много от тях нямат доверие в ядрения чадър на САЩ, защото го възприемат като принцип на селективна намеса – особено при администрацията на Тръмп, която няма интерес от ескалиране на отношенията със Севера. На другия полюс са корейците, според които, ако Сеул получи ядрени оръжия, това завинаги ще го извади от системата за колективна сигурност с Япония и Америка. Нещо повече, може да се стигне до ефект на доминото в Азия и до масово ядрено въоръжаване на азиатските държави. Но това, че ядрените оръжия имат най-силна сдържаща роля, е просто теория, за която нямаме емпирични доказателства, и можем само да се надяваме, че няма да я тестваме.

Следователно причината Корея да не може да бъде единна, не е прищявка на един или друг политик, било то Джо Байдън, Доналд Тръмп или дори Си Дзинпин. Тя се корени във факта, че нито от едната, нито от другата страна се намира желание за успешно следване на слънчевата политика. Корейският полуостров, с други думи, остава в плен на дилемата на сигурността, която може да бъде преодоляна само ако една от страните преустанови своята политика на конфронтация напълно. И тук не става въпрос просто за установяване на диалог. Диалог между двете Кореи има още от края на Корейската война. Както изглежда, желание за диалог има дори у Тръмп, който е ентусиазиран за отношенията си с Ким Чен Ун. Но реални резултати не са налице, защото дилемата на сигурността все още функционира. Взаимният страх между Северна и Южна Корея е много по-мощен генератор на нагласи, отколкото мирното съжителство помежду им, което би било предпоставка за обединението им.

И накрая следва да признаем, че макар съдбата на двата народа да зависи от исканията на хората, ключовата роля за бъдещето на региона е в американски ръце. Рано или късно различията между Русия и Китай по отношение на Корейския полуостров ще изплуват и това ще доведе до различия и между техните партньори. За добро или зло, железният образ на Чичо Сам засега укротява болезнените спомени от японските нашествия в Корея и от унищожаването на династията Чозон.

Но САЩ трябва да бъдат много внимателни, когато регулират нагласите на съюзниците си, защото всеки опит да изискват безпрекословна лоялност към политиката си ще навреди на имиджа им в лицето на Южна Корея и Япония, тъй като двете страни възприемат Америка като съюзник и пазител, а не като началник. Достатъчно е да припомним първите години след края на Корейската война, когато с мълчаливото американско съгласие Южна Корея се управлява от прояпонски елит, наричан подигравателно от корейците „японски мекерета“. Това е напълно в унисон с политиката на доктрината Труман, която цели солидаризиране на всички азиатски съюзници под шапката на следвоенна Япония с цел сдържане на СССР и Китай. Американската подкрепа за Южна Корея следователно може да съдържа в себе си както предпоставките за обединението на полуострова по мирен път – ако корейците го искат, – така и за неговото пълно унищожение.

Amazon Redshift announces history mode for zero-ETL integrations to simplify historical data tracking and analysis

Post Syndicated from Raks Khare original https://aws.amazon.com/blogs/big-data/amazon-redshift-announces-history-mode-for-zero-etl-integrations-to-simplify-historical-data-tracking-and-analysis/

In the ever-evolving landscape of cloud computing and data management, AWS has consistently been at the forefront of innovation. One of the groundbreaking developments in recent years is zero-ETL integration, a set of fully managed integrations by AWS that minimizes the need to build extract, transform, and load (ETL) data pipelines. This post will explore brief history of zero-ETL, its importance for customers, and introduce an exciting new feature: history mode for Amazon Aurora PostgreSQL-Compatible Edition, Amazon Aurora MySQL-Compatible Edition, Amazon Relational Database Service (Amazon RDS) for MySQL, and Amazon DynamoDB zero-ETL integration with Amazon Redshift.

A brief history of zero-ETL integrations

The concept of zero-ETL integrations emerged as a response to the growing complexities and inefficiencies in traditional ETL processes. Traditional ETL processes are time-consuming and complex to develop, maintain, and scale. Although not all use cases can be replaced with zero-ETL, it simplifies the replication and allows you to apply transformation post-replication. This eliminates the need for additional ETL technology between the source database and Amazon Redshift. We at AWS recognized the need for a more streamlined approach to data integration, particularly between operational databases and the cloud data warehouses. The journey of zero-ETL began in late 2022 when we introduced the feature for Aurora MySQL with Amazon Redshift. This feature marked a pivotal moment in streamlining complex data workflows, enabling near real-time data replication and analysis while eliminating the need for ETL processes.

Building on the success of our first zero-ETL integration, we’ve made continuous strides in this space by working backward from our customers’ needs and launching features like data filtering, auto and incremental refresh of materialized views, refresh interval, and more. Furthermore, we increased the breadth of sources to include Aurora PostgreSQL, DynamoDB, and Amazon RDS for MySQL to Amazon Redshift integrations, solidifying our commitment to making it seamless for you to run analytics on your data. The introduction of zero-ETL was not just a technological advancement; it represented a paradigm shift in how organizations could approach their data strategies. By removing the need for intermediate data processing steps, we opened up new possibilities for near real-time analytics and decision-making.

Introducing history mode: A new frontier in data analysis

Zero-ETL has already simplified the data integration, and we’re excited to further enhance the capabilities by announcing a new feature that takes it a step further: history mode with Amazon Redshift. Using history mode with zero-ETL integrations, you can streamline your historical data analysis by maintaining full change data capture (CDC) from the source in Amazon Redshift. History mode enables you to unlock the full potential of your data by seamlessly capturing and retaining historical versions of records across your zero-ETL data sources. You can perform advanced historical analysis, build look back reports, perform trend analysis, and create slowly changing dimensions (SCD) Type 2 tables on Amazon Redshift. This allows you to consolidate your core analytical assets and derive insights across multiple applications, gaining cost savings and operational efficiencies. History mode enables organizations to comply with regulatory requirements for maintaining historical records, facilitating comprehensive data governance and informed decision-making.

Zero-ETL integrations provide a current view of records in near real time, meaning only the latest changes from source databases are retained on Amazon Redshift. With history mode, Amazon Redshift introduces a revolutionary approach to historical data analysis. You can now configure your zero-ETL integrations to track every version of your records in source tables directly in Amazon Redshift, along with the source timestamp with every record version indicating when each record was inserted, modified, or deleted. Because data changes are tracked and retained by Amazon Redshift, this can help you meet your compliance requirements without having to maintain duplicate copies in data sources. In addition, you don’t have to maintain and manage partitioned tables to keep older data intact as separate partitions to version records, and maintain historical data in source databases.

In a data warehouse, the most common dimensional modeling techniques is a star schema, where there is a fact table at the center surrounded by a number of associated dimension tables. A dimension is a structure that categorizes facts and measures in order to enable users to answer business questions. To illustrate an example, in a typical sales domain, customer, time, or product are dimensions and sales transactions is a fact. An SCD is a data warehousing concept that contains relatively static data that can change slowly over a period of time. There are three major types of SCDs maintained in data warehousing: Type 1 (no history), Type 2 (full history), and Type 3 (limited history). CDC is a characteristic of a database that provides an ability to identify the data that changed between two database loads, so that an action can be performed on the changed data.

In this post, we demonstrate how to enable history mode for tables in a zero-ETL integration and capture the full historical data changes as SCD2.

Solution overview

In this use case, we explore how a fictional nationwide retail chain, AnyCompany, uses AWS services to gain valuable insights into their customer base. With multiple locations across the country, AnyCompany aims to enhance their understanding of customer behavior and improve their marketing strategies through two key initiatives:

  • Customer migration analysis – AnyCompany seeks to track and analyze customer relocation patterns, focusing on how geographical moves impact purchasing behavior. By monitoring these changes, the company can adapt its inventory, services, and local marketing efforts to better serve customers in their new locations.
  • Marketing campaign effectiveness – The retailer wants to evaluate the impact of targeted marketing campaigns based on customer demographics at the time of campaign execution. This analysis can help AnyCompany refine its marketing strategies, optimize resource allocation, and improve overall campaign performance.

By closely tracking changes in customer profiles for both geographic movement and marketing responsiveness, AnyCompany is positioning itself to make more informed, data-driven decisions.

In this demonstration, we begin by loading a sample dataset into the source table, customer, in Aurora PostgreSQL-Compatible. To maintain historical records, we enable history mode on the customer table, which automatically tracks changes in Amazon Redshift.

When history mode is turned on, the following columns are automatically added to the target table, customer, in Amazon Redshift to keep track of changes in the source.

Column name Data type Description
_record_is_active Boolean Indicates if a record in the target is currently active in the source. True indicates the record is active.
_record_create_time Timestamp Starting time (UTC) when the source record is active.
_record_delete_time Timestamp Ending time (UTC) when the source record is updated or deleted.

Next, we create a dimension table, customer_dim, in Amazon Redshift with an additional surrogate key column to show an example of creating an SCD table. To optimize query performance for different queries, some of which might be analyzing active or inactive records only while other queries might be analyzing data as of a certain date, we defined the sort key consisting of _record_is_active, _record_create_time, and _record_delete_time attributes in the customer_dim table.

The following figure provides the schema of the source table in Aurora PostgreSQL-Compatible, and the target table and target customer dimension table in Amazon Redshift.
schema

To streamline the data population process, we developed a stored procedure named SP_Customer_Type2_SCD(). This procedure is designed to populate incremental data into the customer_dim table from the replicated customer table. It handles various data changes, including updates, inserts, and deletes in the source table and implementing an SCD2 approach.

Prerequisites

Before you get started, complete the following steps:

  1. Configure your Aurora DB cluster and your Redshift data warehouse with the required parameters and permissions. For instructions, refer to Getting started with Aurora zero-ETL integrations with Amazon Redshift.
  2. Create an Aurora zero-ETL integration with Amazon Redshift.
  3. From an Amazon Elastic Compute Cloud (Amazon EC2) terminal or using AWS CloudShell, SSH into the Aurora PostgreSQL cluster and run the following commands to install psql:
sudo dnf install postgresql15
psql --version
  1. Load the sample source data:
    • Download the TPC-DS sample dataset for the customer table onto the machine running psql.
    • From the EC2 terminal, run the following command to connect to the Aurora PostgreSQL DB using the default super user postgres:
      psql -h <RDS Write Instance Endpoint> -p 5432 -U postgres

    • Run the following SQL command to create the database zetl:
      create database zetl template template1;

    • Change the connection to the newly created database:
      \c zetl

    • Create the customer table (the following example creates it in the public schema):
      CREATE TABLE customer(
          c_customer_id char(16) NOT NULL PRIMARY KEY,
          c_salutation char(10),
          c_first_name char(20),
          c_last_name char(30),
          c_preferred_cust_flag char(1),
          c_birth_day int4,
          c_birth_month int4,
          c_birth_year int4,
          c_birth_country varchar(20),
          c_login char(13),
          c_email_address char(50),
          ca_street_number char(10),
          ca_street_name varchar(60),
          ca_street_type char(15),
          ca_suite_number char(10),
          ca_city varchar(60),
          ca_county varchar(30),
          ca_state char(2),
          ca_zip char(10),
          ca_country varchar(20),
          ca_gmt_offset numeric(5, 2),
          ca_location_type char(20)
      );

    • Run the following command to load customer data from the downloaded dataset after changing the highlighted location of the dataset to your directory path:
      \copy customer from '/home/ec2-user/customer_sample_data.dat' WITH DELIMITER '|' CSV;

    • Run the following query to validate the successful creation of the table and loading of sample data:
      SELECT table_catalog, table_schema, table_name, n_live_tup AS row_count
      FROM information_schema.tables JOIN g_stat_user_tables ON table_name = relname
      WHERE table_type = 'BASE TABLE'
      ORDER BY row_count DESC;

The SQL output should be as follows:

table_catalog | table_schema | table_name | row_count
---------------+--------------+------------+-----------
zetl          | public       | customer   |   1200585
(1 row)

Create a target database in Amazon Redshift

To replicate data from your source into Amazon Redshift, you must create a target database from your integration in Amazon Redshift. For this post, we have already created a source database called zetl in Aurora PostgreSQL-Compatible as part of the prerequisites. Complete the following steps to create the target database:

  1. On the Amazon Redshift console, choose Query editor v2 in the navigation pane.
  2. Run the following commands to create a database called postgres in Amazon Redshift using the zero-ETL integration_id with history mode turned on.
-- Amazon Redshift SQL commands to create database
SELECT integration_id FROM svv_integration; -- copy this result, use in the next sql
CREATE DATABASE "postgres" FROM INTEGRATION '<result from above>' DATABASE "zetl" SET HISTORY_MODE = TRUE;

History mode turned on at the time of target database creation on Amazon Redshift will enable history mode for existing and new tables created in the future.

  1. Run the following query to validate the successful replication of the initial data from the source into Amazon Redshift:
select is_history_mode, table_name, table_state, * from svv_integration_table_state;

The table customer should show table_state as Synced with is_history_mode as true.
histmode-true

Enable history mode for existing zero-ETL integrations

History mode can be enabled for your existing zero-ETL integrations using either the Amazon Redshift console or SQL commands. Based on your use case, you can turn on history mode at the database, schema, or table level. To use the Amazon Redshift console, complete the following steps:

  1. On the Amazon Redshift console, choose Zero-ETL integrations in the navigation pane.
  2. Choose your desired integration.
  3. Choose Manage history mode.
    zelt-integratin

On this page, you can either enable or disable history mode for all tables or a subset of tables.

  1. Select Manage history mode for individual tables and select Turn on for the history mode for the customer
  2. Choose Save changes.
    table-hist-mode
  3. To confirm changes, choose Table statistics and make sure History mode is On for the customer.
    table-stats
  4. Optionally, you can run the following SQL command in Amazon Redshift to enable history mode for the customer table:
ALTER DATABASE "postgres" INTEGRATION SET HISTORY_MODE = TRUE FOR TABLE public.customer;
  1. Optionally, you can enable history mode for all current and tables created in the future in the database:
ALTER DATABASE "postgres" INTEGRATION SET HISTORY_MODE = TRUE FOR ALL TABLES;
  1. Optionally, you can enable history mode for all current and tables created in the future in one or more schemas. The following query enables history mode for all current and tables created in the future for the public schema:
ALTER DATABASE "postgres" INTEGRATION SET HISTORY_MODE = TRUE FOR ALL TABLES IN SCHEMA public;
  1. Run the following query to validate if the customer table has been successfully changed to history mode with the is_history_mode column as true so that it can begin tracking every version (including updates and deletes) of all records changed in the source:
select is_history_mode, table_name, table_state, * from svv_integration_table_state;

Initially, the table will be in ResyncInitiated state before changing to Synced.
table-synced

  1. Run the following query in the zetl database of Aurora PostgreSQL-Compatible to modify a source record and observe the behavior of history mode in the Amazon Redshift target:
UPDATE customer
SET
    ca_suite_number = 'Suite 100',
    ca_street_number = '500',
    ca_street_name = 'Main',
    ca_street_type = 'St.',
    ca_city = 'New York',
    ca_county = 'Manhattan',
    ca_state = 'NY',
    ca_zip = '10001'
WHERE c_customer_id = 'AAAAAAAAAAAKNAAA';
  1. Now run the following query in the postgres database of Amazon Redshift to see all versions of the same record:
SELECT   
    c_customer_id,
    ca_street_number,
    ca_street_name,
    ca_suite_number,
    ca_city,
    ca_county,
    ca_state,
    ca_zip,
    _record_is_active,
    _record_create_time,
    _record_delete_time
FROM postgres.public.customer
WHERE c_customer_id = 'AAAAAAAAAAAKNAAA';

Zero-ETL integrations with history mode has inactivated the old record with the _record_is_active column value to false and created a new record with _record_is_active as true. You can also see how it maintains the _record_create_time and _record_delete_time column values for both records. The inactive record has a delete timestamp that matches the active record’s create timestamp.
table-history

Load incremental data in an SCD2 table

Complete the following steps to create an SCD2 table and implement an incremental data load process in a regular database of Amazon Redshift, in this case dev:

  1. Create an empty customer SDC2 table called customer_dim with SCD fields. The table also has DISTSTYLE AUTO and SORTKEY columns _record_is_active, _record_create_time, and _record_delete_time. When you define a sort key on a table, Amazon Redshift can skip reading entire blocks of data for that column. It can do so because it tracks the minimum and maximum column values stored on each block and can skip blocks that don’t apply to the predicate range.
CREATE TABLE dev.public.customer_dim (
    c_customer_sk bigint NOT NULL DEFAULT 0 ENCODE raw distkey,
    c_customer_id character varying(19) DEFAULT '' :: character varying ENCODE lzo,
    c_salutation character varying(12) ENCODE bytedict,
    c_first_name character varying(24) ENCODE lzo,
    c_last_name character varying(36) ENCODE lzo,
    c_preferred_cust_flag character varying(1) ENCODE lzo,
    c_birth_day integer ENCODE az64,
    c_birth_month integer ENCODE az64,
    c_birth_year integer ENCODE az64,
    c_birth_country character varying(24) ENCODE bytedict,
    c_login character varying(15) ENCODE lzo,
    c_email_address character varying(60) ENCODE lzo,
    ca_street_number character varying(12) ENCODE lzo,
    ca_street_name character varying(72) ENCODE lzo,
    ca_street_type character varying(18) ENCODE bytedict,
    ca_suite_number character varying(12) ENCODE bytedict,
    ca_city character varying(72) ENCODE lzo,
    ca_county character varying(36) ENCODE lzo,
    ca_state character varying(2) ENCODE lzo,
    ca_zip character varying(12) ENCODE lzo,
    ca_country character varying(24) ENCODE lzo,
    ca_gmt_offset numeric(5, 2) ENCODE az64,
    ca_location_type character varying(24) ENCODE bytedict,
    _record_is_active boolean ENCODE raw,
    _record_create_time timestamp without time zone ENCODE az64,
    _record_delete_time timestamp without time zone ENCODE az64,
    PRIMARY KEY (c_customer_sk)
) SORTKEY (
    _record_is_active,
    _record_create_time,
    _record_delete_time
);

Next, you create a stored procedure called SP_Customer_Type2_SCD() to populate incremental data in the customer_dim SCD2 table created in the preceding step. The stored procedure contains the following components:

    • First, it fetches the max _record_create_time and max _record_delete_time for each customer_id.
    • Then, it compares the output of the preceding step with the ongoing zero-ETL integration replicated table for records created after the max creation time in the dimension table or the record in the replicated table with _record_delete_time after the max _record_delete_time in the dimension table for each customer_id.
    • The output of the preceding step captures the changed data between the replicated customer table and target customer_dim dimension table. The interim data is staged to a customer_stg table, which is ready to be merged with the target table.
    • During the merge process, records that need to be deleted are marked with _record_delete_time and _record_is_active is set to false, whereas newly created records are inserted into the target table customer_dim with _record_is_active as true.
  1. Create the stored procedure with the following code:
CREATE OR REPLACE PROCEDURE public.sp_customer_type2_scd()
LANGUAGE plpgsql
AS $$
    BEGIN

    DROP TABLE IF EXISTS cust_latest;

    -- Create temp table with latest record timestamps
         CREATE TEMP TABLE cust_latest DISTKEY (c_customer_id) 
    AS
        SELECT
            c_customer_id,
            max(_record_create_time) AS _record_create_time,
            max(_record_delete_time) AS _record_delete_time
        FROM customer_dim 
        GROUP BY c_customer_id;
    
    DROP TABLE IF EXISTS customer_stg;

    -- Identify and stage changed records
    CREATE TEMP TABLE customer_stg 
    AS           
    SELECT
            ABS(fnv_hash(cust.c_customer_id)) as customer_sk,
            cust.*
            FROM
                postgres.public.customer cust
LEFT OUTER JOIN cust_latest ON cust.c_customer_id = cust_latest.c_customer_id
WHERE (cust._record_create_time > NVL(cust_latest._record_create_time, '1099-01-01 01:01:01') AND cust._record_is_active is true)
OR (cust._record_delete_time > NVL(cust_latest._record_delete_time, '1099-01-01 01:01:01') AND cust._record_is_active is false);

    -- Merge changes to customer dimension table
    MERGE INTO public.customer_dim 
    USING customer_stg stg 
    ON customer_dim.c_customer_id = stg.c_customer_id
        AND customer_dim._record_is_active = TRUE
        AND stg._record_is_active = false
    WHEN MATCHED THEN
        UPDATE
        SET
            _record_is_active = stg._record_is_active,
            _record_create_time = stg._record_create_time,
            _record_delete_time = stg._record_delete_time
    WHEN NOT MATCHED THEN
        INSERT
        VALUES
            (
                stg.customer_sk,
                stg.c_customer_id,
                stg.c_salutation,
                stg.c_first_name,
                stg.c_last_name,
                stg.c_preferred_cust_flag,
                stg.c_birth_day,
                 	     stg.c_birth_month,
                stg.c_birth_year,
                stg.c_birth_country,
                stg.c_login,
                stg.c_email_address,
                stg.ca_street_number,
                stg.ca_street_name,
                stg.ca_street_type,
                stg.ca_suite_number,
                stg.ca_city,
                stg.ca_county,
                stg.ca_state,
                stg.ca_zip,
                stg.ca_country,
                stg.ca_gmt_offset,
                stg.ca_location_type,
                stg._record_is_active,
                stg._record_create_time,
                stg._record_delete_time
            );

    END;
    $$
  1. Run and schedule the stored procedure to load the initial and ongoing incremental data into the customer_dim SCD2 table:
CALL SP_Customer_Type2_SCD();
  1. Validate the data in the customer_dim table for the same customer with a changed address:
SELECT
    c_customer_id,
    ca_street_number,
    ca_street_name,
    ca_suite_number,
    ca_city,
    ca_county,
    ca_state,
    ca_zip,
    _record_is_active,
    _record_create_time,
    _record_delete_time
FROM customer_dim
WHERE c_customer_id = 'AAAAAAAAAAAKNAAA';

dim-history

You have successfully implemented an incremental load strategy for the customer SCD2 table. Going forward, all changes to customer will be tracked and maintained in this customer dimension table by running the stored procedure. This enables you to analyze customer data at a desired point in time for varying use cases, for example, performing customer migration analysis and seeing how geographical moves impact purchasing behavior, or marketing campaign effectiveness to analyze the impact of targeted marketing campaigns on customer demographics at the time of campaign execution.

Industry use cases for history mode

The following are other industry use cases enabled by history mode between operational data stores and Amazon Redshift:

  • Financial auditing or regulatory compliance – Track changes in financial records over time to support compliance and audit requirements. History mode allows auditors to reconstruct the state of financial data at any point in time, which is crucial for investigations and regulatory reporting.
  • Customer journey analysis – Understand how customer data evolves to gain insights into behavior patterns and preferences. Marketers can analyze how customer profiles change over time, informing personalization strategies and lifetime value calculations.
  • Supply chain optimization – Analyze historical inventory and order data to identify trends and optimize stock levels. Supply chain managers can review how demand patterns have shifted over time, improving forecasting accuracy.
  • HR analytics – Track employee data changes over time for better workforce planning and performance analysis. HR professionals can analyze career progression, salary changes, and skill development trends across the organization.
  • Machine learning model auditing – Data scientists can use historical data to train models, compare predictions vs. actuals to improve accuracy, and help explain model behavior and identify potential biases over time.
  • Hospitality and airline industry use cases – For example:
    • Customer service – Access historical reservation data to swiftly address customer queries, enhancing service quality and customer satisfaction.
    • Crew scheduling – Track crew schedule changes to help comply with union contracts, maintaining positive labor relations and optimizing workforce management.
    • Data science applications – Use historical data to train models on multiple scenarios from different time periods. Compare predictions against actuals to improve model accuracy for key operations such as airport gate management, flight prioritization, and crew scheduling optimization.

Best practices

If your requirement is to separate active and inactive records, you can use _record_is_active as the first sort key. For other patterns where you want to analyze data as of a specific date in the past, irrespective of whether data is active or inactive, _record_create_time and _record_delete_time can be added as sort keys.

History mode retains record versions, which will increase the table size in Amazon Redshift and could impact query performance. Therefore, periodically perform DML deletes for outdated record versions (delete data beyond a certain timeframe if not needed for analysis). When executing these deletions, maintain data integrity by deleting across all related tables. Vacuuming also becomes necessary when you perform DML deletes on records whose versioning is no longer required. To improve auto vacuum delete efficiency, Amazon Redshift auto vacuum delete is more efficient when operating on bulk deletes. You can monitor vacuum progression using the SYS_VACUUM_HISTORY table.

Clean up

Complete the following steps to clean up your resources:

  1. Delete the Aurora PostgreSQL cluster.
  2. Delete the Redshift cluster.
  3. Delete the EC2 instance.

Conclusion

Zero-ETL integrations have already made significant strides in simplifying data integration and enabling near real-time analytics. With the addition of history mode, AWS continues to innovate, providing you with even more powerful tools to derive value from your data.

As businesses increasingly rely on data-driven decision-making, zero-ETL with history mode will be crucial in maintaining a competitive edge in the digital economy. These advancements not only streamline data processes but also open up new avenues for analysis and insight generation.

To learn more about zero-ETL integration with history mode, refer to Zero-ETL integrations and Limitations. Get started with zero-ETL on AWS by creating a free account today!


About the Authors

Raks KhareRaks Khare is a Senior Analytics Specialist Solutions Architect at AWS based out of Pennsylvania. He helps customers across varying industries and regions architect data analytics solutions at scale on the AWS platform. Outside of work, he likes exploring new travel and food destinations and spending quality time with his family.

Jyoti Aggarwal is a Product Management Lead for AWS zero-ETL. She leads the product and business strategy, including driving initiatives around performance, customer experience, and security. She brings along an expertise in cloud compute, data pipelines, analytics, artificial intelligence (AI), and data services including databases, data warehouses and data lakes.

Gopal Paliwal is a Principal Engineer for Amazon Redshift, leading the software development of ZeroETL initiatives for Amazon Redshift.

Harman Nagra is a Principal Solutions Architect at AWS, based in San Francisco. He works with global financial services organizations to design, develop, and optimize their workloads on AWS.

Sumanth Punyamurthula is a Senior Data and Analytics Architect at Amazon Web Services with more than 20 years of experience in leading large analytical initiatives, including analytics, data warehouse, data lakes, data governance, security, and cloud infrastructure across travel, hospitality, financial, and healthcare industries.

Streamline AWS WAF log analysis with Apache Iceberg and Amazon Data Firehose

Post Syndicated from Charishma Makineni original https://aws.amazon.com/blogs/big-data/streamline-aws-waf-log-analysis-with-apache-iceberg-and-amazon-data-firehose/

Organizations are rapidly expanding their digital presence, creating opportunities to serve customers better through web applications. AWS WAF logs play a vital role in this expansion by enabling organizations to proactively monitor security, enforce compliance, and strengthen application defense. AWS WAF log analysis is essential across many industries, including banking, retail, and healthcare, each needing to deliver secure digital experiences.

To optimize their security operations, organizations are adopting modern approaches that combine real-time monitoring with scalable data analytics. They are using data lake architectures and Apache Iceberg to efficiently process large volumes of security data while minimizing operational overhead. Apache Iceberg combines enterprise reliability with SQL simplicity when working with security data stored in Amazon Simple Storage Service (Amazon S3), enabling organizations to focus on security insights rather than infrastructure management.

Apache Iceberg enhances security analytics through several key capabilities. It seamlessly integrates with various AWS services and analysis tools while supporting concurrent read-write operations for simultaneous log ingestion and analysis. Its time travel feature enables thorough security forensics and incident investigation, and its schema evolution support allows teams to adapt to emerging security patterns without disrupting existing workflows. These capabilities make Apache Iceberg an ideal choice for building robust security analytics solutions. However, organizations often struggle when building their own solutions to deliver data to Apache Iceberg tables. These include managing complex extract, transform, and load (ETL) processes, handling schema validation, providing reliable delivery, and maintaining custom code for data transformations. Teams must also build resilient error handling, implement retry logic, and manage scaling infrastructure—all while maintaining data consistency and high availability. These challenges take valuable time away from analyzing security data and deriving insights.

To address these challenges, Amazon Data Firehose provides real-time data delivery to Apache Iceberg tables within seconds. Firehose delivers high reliability across multiple Availability Zones while automatically scaling to match throughput requirements. It is fully managed and requires no infrastructure management or custom code development. Firehose delivers streaming data with configurable buffering options that can be optimized for near-zero latency. It also provides built-in data transformation, compression, and encryption capabilities, along with automatic retry mechanisms to provide reliable data delivery. This makes it an ideal choice for streaming AWS WAF logs directly into a data lake while minimizing operational overhead.

In this post, we demonstrate how to build a scalable AWS WAF log analysis solution using Firehose and Apache Iceberg. Firehose simplifies the entire process—from log ingestion to storage—by allowing you to configure a delivery stream that delivers AWS WAF logs directly to Apache Iceberg tables in Amazon S3. The solution requires no infrastructure setup and you pay only for the data you process.

Solution overview

To implement this solution, you first configure AWS WAF logging to capture web traffic information. This captures detailed information about traffic analyzed by the web access control lists (ACLs). Each log entry includes the request timestamp, detailed request information, and rule matches that were triggered. These logs are continuously streamed to Firehose in real time.

Firehose writes these logs into an Apache Iceberg table, which is stored in Amazon S3. When Firehose delivers data to the S3 table, it uses the AWS Glue Data Catalog to store and manage table metadata. This metadata includes schema information, partition details, and file locations, enabling seamless data discovery and querying across AWS analytics services.

Finally, security teams can analyze data in the Apache Iceberg tables using various AWS services, including Amazon Redshift, Amazon Athena, Amazon EMR, and Amazon SageMaker. For this demonstration, we use Athena to run SQL queries against the security logs.

The following diagram illustrates the solution architecture.

 

The implementation consists of four steps:

  1. Deploy the base infrastructure using AWS CloudFormation.
  2. Create an Apache Iceberg table using an AWS Glue notebook.
  3. Create a Firehose stream to handle the log data.
  4. Configure AWS WAF logging to send data to the Apache Iceberg table through the Firehose stream.

You can deploy the required resources into your AWS environment in the US East (N. Virginia) AWS Region using a CloudFormation template. This template creates an S3 bucket for storing AWS WAF logs, an AWS Glue database for the Apache Iceberg tables, and the AWS Identity and Access Management (IAM) roles and policies needed for the solution.

Prerequisites

Before you get started, make sure you have the following prerequisites:

  • An AWS account with access to the US East (N. Virginia) Region
  • AWS WAF configured with a web ACL in the US East (N. Virginia) Region

If you don’t have AWS WAF set up, refer to the AWS WAF Workshop to create a sample web application with AWS WAF.

AWS WAF logs use case-sensitive field names (like httpRequest and webaclId). For successful log ingestion, this solution uses the Apache Iceberg API through an AWS Glue job to create tables—this is a reliable approach that preserves the exact field names from the AWS WAF logs. Although AWS Glue crawlers and Athena DDLs offer convenient ways to create Apache Iceberg tables, they convert mixed-case column names to lowercase, which can affect AWS WAF log processing. By using an AWS Glue job with the Apache Iceberg API, case-sensitivity of column names is preserved, providing proper mapping between AWS WAF log fields and table columns.

Deploy the CloudFormation stack

Complete the following steps to deploy the solution resources with AWS CloudFormation:

  1. Sign in to the AWS CloudFormation console.
  2. Choose Launch Stack.
    Launch Cloudformation Stack
  3. Choose Next.
  4. For Stack name, leave as WAF-Firehose-Iceberg-Stack.
  5. Under Parameters, specify whether AWS Lake Formation permissions are to be used for the AWS Glue tables.
  6. Choose Next.

  1. Select I acknowledge that AWS CloudFormation might create IAM resources with custom names and choose Next.

 

  1. Review the deployment and choose Submit.

 

The stack takes several minutes to deploy. After the deployment is complete, you can review the resources created by navigating to the Resources tab on the CloudFormation stack.

Create an Apache Iceberg table

Before setting up the Firehose delivery stream, you must create the destination Apache Iceberg table in the Data Catalog. This is done using AWS Glue jobs and the Apache Iceberg API, as discussed earlier. Complete the following steps to create an Apache Iceberg table:

  1. On the AWS Glue console, choose Notebooks under ETL jobs in the navigation pane.

 

  1. Choose Notebook option under Create job.

 

  1. Under Options, select Start fresh.
  2. For IAM role, choose WAF-Firehose-Iceberg-Stack-GlueServiceRole-*.
  3. Choose Create notebook.

  1. Enter the following configuration command in the notebook to configure the Spark session with Apache Iceberg extensions. Be sure to update the configuration for sql.catalog.glue_catalog.warehouse to the S3 bucket created by the CloudFormation template.
%%configure
{
    "--conf": "spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions --conf spark.sql.catalog.glue_catalog=org.apache.iceberg.spark.SparkCatalog --conf spark.sql.catalog.glue_catalog.warehouse=s3://<S3BucketName>/waflogdata --conf spark.sql.catalog.glue_catalog.catalog-impl=org.apache.iceberg.aws.glue.GlueCatalog --conf spark.sql.catalog.glue_catalog.io-impl=org.apache.iceberg.aws.s3.S3FileIO",
    "--datalake-formats": "iceberg"
}

  1. Enter the following SQL in the AWS Glue notebook to create the Apache Iceberg table:
# Note: This code uses Glue version 5.0 (as of April 2024)
# Please check AWS Glue release notes for the latest version and update accordingly:
# https://docs.aws.amazon.com/glue/latest/dg/release-notes.html
# To update: Change the %glue_version parameter below to the latest version

%idle_timeout 2880
%glue_version 5.0
%worker_type G.1X
%number_of_workers 5

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
from pyspark.conf import SparkConf

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)

spark.sql(""" CREATE TABLE glue_catalog.waf_logs_db.firehose_waf_logs(
  `timestamp` bigint,
  `formatVersion` int,
  `webaclId` string,
  `terminatingRuleId` string,
  `terminatingRuleType` string,
  `action` string,
  `terminatingRuleMatchDetails` array <
                                    struct <
                                        conditiontype: string,
                                        sensitivitylevel: string,
                                        location: string,
                                        matcheddata: array < string >
                                          >
                                     >,
  `httpSourceName` string,
  `httpSourceId` string,
  `ruleGroupList` array <
                      struct <
                          rulegroupid: string,
                          terminatingrule: struct <
                                              ruleid: string,
                                              action: string,
                                              rulematchdetails: array <
                                                                   struct <
                                                                       conditiontype: string,
                                                                       sensitivitylevel: string,
                                                                       location: string,
                                                                       matcheddata: array < string >
                                                                          >
                                                                    >
                                                >,
                          nonterminatingmatchingrules: array <
                                                              struct <
                                                                  ruleid: string,
                                                                  action: string,
                                                                  overriddenaction: string,
                                                                  rulematchdetails: array <
                                                                                       struct <
                                                                                           conditiontype: string,
                                                                                           sensitivitylevel: string,
                                                                                           location: string,
                                                                                           matcheddata: array < string >
                                                                                              >
                                                                   >,
                                                                  challengeresponse: struct <
                                                                            responsecode: string,
                                                                            solvetimestamp: string
                                                                              >,
                                                                  captcharesponse: struct <
                                                                            responsecode: string,
                                                                            solvetimestamp: string
                                                                              >
                                                                    >
                                                             >,
                          excludedrules: string
                            >
                       >,
`rateBasedRuleList` array <
                         struct <
                             ratebasedruleid: string,
                             limitkey: string,
                             maxrateallowed: int
                               >
                          >,
  `nonTerminatingMatchingRules` array <
                                    struct <
                                        ruleid: string,
                                        action: string,
                                        rulematchdetails: array <
                                                             struct <
                                                                 conditiontype: string,
                                                                 sensitivitylevel: string,
                                                                 location: string,
                                                                 matcheddata: array < string >
                                                                    >
                                                             >,
                                        challengeresponse: struct <
                                                            responsecode: string,
                                                            solvetimestamp: string
                                                             >,
                                        captcharesponse: struct <
                                                            responsecode: string,
                                                            solvetimestamp: string
                                                             >
                                          >
                                     >,
  `requestHeadersInserted` array <
                                struct <
                                    name: string,
                                    value: string
                                      >
                                 >,
  `responseCodeSent` string,
  `httpRequest` struct <
                    clientip: string,
                    country: string,
                    headers: array <
                                struct <
                                    name: string,
                                    value: string
                                      >
                                 >,
                    uri: string,
                    args: string,
                    httpversion: string,
                    httpmethod: string,
                    requestid: string
                      >,
  `labels` array <
               struct <
                   name: string
                     >
                >,
  `CaptchaResponse` struct <
                        responsecode: string,
                        solvetimestamp: string,
                        failureReason: string
                          >,
  `ChallengeResponse` struct <
                        responsecode: string,
                        solvetimestamp: string,
                        failureReason: string
                        >,
  `ja3Fingerprint` string,
  `overSizeFields` string,
  `requestBodySize` int,
  `requestBodySizeInspectedByWAF` int
)
USING iceberg
TBLPROPERTIES ("format-version"="2")
""")
job.commit()

  1. Navigate to the Data Catalog and waf_logs_db database to confirm the table firehose_waf_logs is created.

Create a Firehose stream

Complete the following steps to create a Firehose stream:

  1. On the Data Firehose console, choose Create Firehose stream.

  1. Choose Direct PUT for Source and Apache Iceberg Tables for Destination.

  1. For Firehose stream name, enter aws-waf-logs-firehose-iceberg-1.
  1. In the Destination settings section, enable Inline parsing for routing information. Because we’re sending all records to one table, specify the destination database and table names:
    1. For Database expression, enter "waf_logs_db".
    2. For Table expression, enter "firehose_waf_logs".

Make sure to include double quotation marks to use the literal value for the database and table name. If you don’t use double quotation marks, Firehose assumes that this is a JSON query expression and will attempt to parse the expression when processing your stream and fail. Firehose can also route to different Apache Iceberg Tables based on the content of the data. For more information, refer to Route incoming records to different Iceberg Tables.

  1. For S3 backup bucket, enter the S3 bucket created by the CloudFormation template.
  2. For S3 backup bucket error output prefix, enter error/events-1/.

  1. Under Advanced settings, select Enable server-side encryption for source records in Firehose stream.

  1. For Existing IAM roles, choose the role that starts with WAF-Firehose-Iceberg-stack-FirehoseIAMRole-*, created by the CloudFormation template.
  2. Choose Create Firehose stream.

Configure AWS WAF logs to the Firehose stream

Complete the following steps to configure AWS WAF logs to the Firehose stream.

  1. On the AWS WAF console, choose Web ACLs in the navigation pane.

  1. Choose your web ACL.
  2. On the Logging and metrics tab, choose Enable.

  1. For Amazon Data Firehose stream, choose the stream aws-waf-logs-firehose-iceberg-1.
  2. Choose Save.

Query and analyze the logs

You can query the data you’ve written to your Apache Iceberg tables using different processing engines, such as Apache Spark, Apache Flink, or Trino. In this example, we use Athena to query AWS WAF logs data stored in Apache Iceberg tables. Complete the following steps:

  1. On the Athena console, choose Settings in the top right corner.
  2. For Location of query result, enter the S3 bucket created by the CloudFormation template

s3://<S3BucketName>/athena/

  1. Enter the AWS account ID for Expected bucket owner and choose save.

  1. In the query editor, in Tables and views, choose the options menu next to firehose_waf_logs and choose Preview Table.

You should be able to see the AWS WAF logs in the Apache Iceberg tables by using Athena.

The following are some additional useful example queries:

  • Identify potential attack sources by analyzing blocked IP addresses:
-- Top 10 blocked IP addresses
SELECT httpRequest.clientip, COUNT() as block_count
FROM waf_logs_db.firehose_waf_logs
WHERE action = 'BLOCK'
GROUP BY httpRequest.clientip
ORDER BY block_count DESC
LIMIT 10;
  • Monitor attack patterns and trends over time:
-- Rate of blocked requests over time
SELECT DATE_TRUNC('hour', FROM_UNIXTIME(timestamp/1000)) as hour,
       COUNT() as request_count
FROM waf_logs_db.firehose_waf_logs
WHERE action = 'BLOCK'
GROUP BY DATE_TRUNC('hour', FROM_UNIXTIME(timestamp/1000))
ORDER BY hour;

Apache Iceberg table optimization

Although Firehose enables efficient streaming of AWS WAF logs into Apache Iceberg tables, the nature of streaming writes can result in many small files being created. This is because Firehose delivers data based on its buffering configuration, which can lead to suboptimal query performance. To address this, regular table optimization is recommended.

There are two recommended table optimization approaches:

  • Compaction – Data compaction merges small data files to reduce storage usage and improve read performance. Data files are merged and rewritten to remove obsolete data and consolidate fragmented data into larger, more efficient files.
  • Storage optimization – You can manage storage overhead by removing older, unnecessary snapshots and their associated underlying files. Additionally, this includes periodically deleting orphan files to maintain efficient storage utilization and optimal query performance.

These optimizations can be implemented using either the Data Catalog or Athena.

Table optimization using the Data Catalog

The Data Catalog provides automatic table optimization features. Within the table optimization feature, you can configure specific optimizers for compaction, snapshot retention, and orphan file deletion. A table optimization schedule can be managed and status can be monitored from the AWS Glue console.

Table optimization using Athena

Athena supports manual optimization through SQL commands. The OPTIMIZE command rewrites small files into larger files and applies file compaction:

OPTIMIZE waf_logs_db.firehose_waf_logs REWRITE DATA USING BIN_PACK 

The VACUUM command removes old snapshots and cleans up expired data files:

ALTER TABLE waf_logs_db.firehose_waf_logs SET TBLPROPERTIES (
  'vacuum_max_snapshot_age_seconds'='259200'
)
VACUUM waf_logs_db.firehose_waf_logs

You can monitor the table’s optimization status using the following query:

SELECT * FROM "waf_logs_db"."firehose_waf_logs$files"

Clean up

To avoid future charges, complete the following steps:

  1. Empty the S3 bucket.
  2. Delete the CloudFormation stack.
  3. Delete the Firehose stream.
  4. Disable AWS WAF logging.

Conclusion

In this post, we demonstrated how to build an AWS WAF log analytics pipeline using Firehose to deliver AWS WAF logs to Apache Iceberg tables on Amazon S3. The solution handles large-scale AWS WAF log processing without requiring complex code or infrastructure management. Although this post focused on Apache Iceberg tables as the destination, Data Firehose also seamlessly integrates with Amazon S3 tables. To optimize your tables for querying, Amazon S3 Tables continuously performs automatic maintenance operations, such as compaction, snapshot management, and unreferenced file removal. These operations increase table performance by compacting smaller objects into fewer, larger files.

To get started with your own implementation, try the solution in your AWS account and explore the following resources for additional features and best practices:


About the Authors

Charishma Makineni is a Senior Technical Account Manager at AWS. She provides strategic technical guidance for Independent Software Vendors (ISVs) to build and optimize solutions on AWS. She specializes in Big Data and Analytics technologies, helping organizations optimize their data-driven initiatives on AWS.

Phaneendra Vuliyaragoli is a Product Management Lead for Amazon Data Firehose at AWS. In this role, Phaneendra leads the product and go-to-market strategy for Amazon Data Firehose.

A milestone for reproducible openSUSE

Post Syndicated from corbet original https://lwn.net/Articles/1010629/

The Reproducible-openSUSE project has announced
that it has created a usable version of openSUSE with 100% reproducible
packages.

[Bernhard] Wiedemann took on this 4-month-long project to create a
fork of openSUSE that has 100% bit-reproducible packages. So far
ring0 (aka bootstrap) and ring1 with 3,300 software packages have
all successfully been patched and tested.

This build is not yet recommended for production use, though.

The collective thoughts of the interwebz