Pieces

https://www.scottsantens.com/the-hidden-reasons-authoritarianism-is-growing-and-how-to-reverse-it-ubi/
webpage banner

The Hidden Reasons Authoritarianism Is Growing — And How to Reverse It

This article explores the psychological roots of rising authoritarianism, framing it as a dynamic between 'steadfasts' who value security and sameness, and 'explorers' who value diversity and novelty. Drawing on the work of Dr. Karen Stenner, it argues that authoritarian tendencies are 'activated' by perceived normative threats like inequality and social division. The author posits that authoritarianism can be 'deactivated' through normative reassurance, expanding the definition of the 'in-group,' and reducing cognitive load. Universal Basic Income (UBI) is presented as a key policy solution to reduce these threats, foster security, and thus strengthen democracy.

The Hidden Reasons Authoritarianism Is Growing — And How to Reverse It
Tomato, Basil, Pasta Salad
cherry tomato
olive oil
garlic
basil
pepper
salt
red pepper flakes
parmesan
spaghetti
Tomato, Basil, Pasta Salad
https://www.newyorker.com/magazine/2024/10/21/alexei-navalny-patriot-memoir
webpage banner

Prison Diaries: An Excerpt from Alexei Navalny’s Memoir, “Patriot”

An excerpt from Alexei Navalny's memoir, 'Patriot,' which he began writing after being poisoned with Novichok in 2020. The excerpts are diary entries from 2022 to 2024, written from various Russian prisons, including the 'special regime' colony 'Polar Wolf.' Navalny reflects on his imprisonment, his political convictions, the nature of the Putin regime, and his unwavering hope for a democratic Russia. He shares personal anecdotes, details of his harsh prison life, and messages of courage to his supporters.

Prison Diaries: An Excerpt from Alexei Navalny’s Memoir, “Patriot”
https://challahscript.com/what_i_wish_someone_told_me_about_postgres

What I Wish Someone Told Me About Postgres

A comprehensive guide for developers detailing practical advice and common pitfalls when working with PostgreSQL. The article covers data normalization, psql customization, effective indexing strategies, the intricacies of database locks and long-running transactions, and the careful use of the JSONB data type.

What I Wish Someone Told Me About Postgres
https://anderegg.ca/2024/11/15/maybe-bluesky-has-won

Maybe Bluesky has “won”

November has sucked so far. One upside of the terrible nonsense is that more people are fleeing X. Many are choosing Bluesky. I’ve seen a bunch of takes about this recently, but I keep seeing things I disagree with. I figure that’s a good enough excuse to write more about this weird-assed social network.

Maybe Bluesky has “won”
https://www.washingtonpost.com/food/2024/04/27/vegan-cheese-good-food-awards-climax/
webpage banner

A vegan cheese beat dairy in a big competition. Then the plot curdled…

An article discussing a competition where a vegan cheese product outperformed traditional dairy cheeses, and the subsequent controversy and developments that followed.

A vegan cheese beat dairy in a big competition. Then the plot curdled…
https://www.newyorker.com/magazine/2024/10/14/silicon-valley-the-new-lobbying-monster
webpage banner

Silicon Valley, the New Lobbying Monster

From crypto to A.I., the tech sector is pouring millions into super PACS that intimidate politicians into supporting its agenda.

Silicon Valley, the New Lobbying Monster
https://www.theatlantic.com/science/archive/2024/11/how-brain-processes-zero/680680/
webpage banner

Zero May Be Humankind’s Greatest Invention

This article, originally from Quanta Magazine, explores the history and cognitive neuroscience of the number zero. It highlights two recent, independent studies revealing that while the brain processes zero on a mental number line like other numbers, it also gives it a special status, potentially linked to the broader concept of absence. The research delves into how our minds create a mathematical object out of nothing, a process that took humanity centuries to formalize.

Zero May Be Humankind’s Greatest Invention
Becky Chambers The Long Way to a Small, Angry Planet
The Long Way to a Small, Angry Planet
The Long Way to a Small, Angry Planet
https://news.mit.edu/2024/when-muscles-work-out-they-help-neurons-grow-1112
webpage banner

When muscles work out, they help neurons to grow, a new study shows

Exercise can have benefits at the level of neurons, through chemical and mechanical effects, MIT researchers find. The discovery could inform exercise-related therapies for repairing damaged and deteriorating nerves.

When muscles work out, they help neurons to grow, a new study shows
https://www.youtube.com/shorts/fVNLT5wKl2g
webpage banner

Very Evil Stafford Gambit

the Stafford gambit gone wrong

Very Evil Stafford Gambit
https://www.theatlantic.com/ideas/archive/2025/07/supreme-court-third-country-deportations/683445/
webpage banner

The Inscrutable Supreme Court

Paul Rosenzweig argues that the Supreme Court's unexplained order in Department of Homeland Security v. D. V. D. is a threat to the rule of law. By allowing the deportation of individuals to third countries without a hearing or any provided reasoning, the Court rewards the Trump administration's defiance of lower court orders. Rosenzweig criticizes the 6-3 majority for abandoning the judicial principle of explaining its decisions, concluding that the action is one of raw power, not law, turning the Court into an authoritarian body.

The Inscrutable Supreme Court
https://www.youtube.com/watch?v=rRXmK0p94dg
webpage banner

Rebel's Chess Opening: The Dummy Trap

a music video demonstrating the 'Dummy Trap' in a chess opening

Rebel's Chess Opening: The Dummy Trap
https://www.economist.com/obituary/2025/07/03/john-robbins-had-serious-doubts-about-the-family-business
webpage banner

John Robbins had serious doubts about the family business

An obituary for John Robbins, the heir to the Baskin-Robbins ice cream fortune, who rejected his inheritance to become a prominent advocate for veganism, simple living, and animal rights. His influential book, "Diet for a New America," criticized the health impacts of the modern food industry. The article recounts his life, his strained but eventually reconciled relationship with his father, and his lasting impact on health and wellness movements.

John Robbins had serious doubts about the family business
https://www.theatlantic.com/ideas/archive/2025/07/public-health-politicization/683409/
webpage banner

How Public Health Discredited Itself

The article argues that the public health profession has been corrupted by politics over the past 50 years, shifting from fighting infectious diseases to advancing ideological goals. The author, John Tierney, cites several examples, including flawed dietary guidelines on fat and salt, the crusade against less harmful nicotine alternatives like vaping, and most notably, the response to the COVID-19 pandemic. He contends that lockdowns, mask mandates, and vaccine policies were often based on political bias rather than scientific evidence, leading to a significant loss of public trust. The piece concludes that to regain credibility, public health must return to its original principles of evidence-based science and humility.

How Public Health Discredited Itself
https://zarar.dev/good-software-development-habits/
webpage banner

Good software development habits

This post is not advice, it's what's working for me. It's easy to pick up bad habits and hard to create good ones. Writing down what's working for me helps me maintain any good habits I've worked hard to develop.

Good software development habits
https://yalereview.org/article/chris-ware-richard-scarry
webpage banner

Chris Ware on Richard Scarry and the Art of Children's Literature

The illustrator Chris Ware surveys the work of Richard Scarry.

Chris Ware on Richard Scarry and the Art of Children's Literature
https://signal.org/docs/specifications/doubleratchet/
webpage banner

The Double Ratchet Algorithm

The Double Ratchet algorithm is a key management protocol used by two parties to exchange encrypted messages, based on a shared secret key. It uses a combination of a symmetric-key ratchet and a Diffie-Hellman ratchet to provide both forward and post-compromise security. The symmetric-key ratchet ensures that every message is encrypted with a distinct key, while the Diffie-Hellman ratchet periodically updates keys based on Diffie-Hellman outputs, protecting against the compromise of keys. The protocol is designed to handle out-of-order messages and also includes an optional feature for header encryption to protect metadata. This paper provides a detailed specification of the algorithm, covering its components, state, initialization, and the processes for encryption and decryption, as well as security considerations and recommendations for implementation.

The Double Ratchet Algorithm
https://theoatmeal.com/comics/forbidden_love
webpage banner

No love is forbidden

A comic by The Oatmeal titled 'No love is forbidden' which involves corn.

No love is forbidden
https://www.nytimes.com/2021/12/09/technology/birds-arent-real-gen-z-misinformation.html
webpage banner

Birds Aren’t Real, or Are They? Inside a Gen Z Conspiracy Theory.

Peter McIndoe, the 23-year-old creator of the viral Birds Aren’t Real movement, is ready to reveal what the effort is really about. The movement is a parody social movement with a purpose. In a post-truth world dominated by online conspiracy theories, young people have coalesced around the effort to thumb their nose at, fight and poke fun at misinformation. It’s Gen Z’s attempt to upend the rabbit hole with absurdism.

Birds Aren’t Real, or Are They? Inside a Gen Z Conspiracy Theory.
https://resobscura.substack.com/p/a-very-deep-history-of-halloween
webpage banner

A very deep history of Halloween

An exploration of the historical roots of Halloween, tracing its origins back to ancient celebrations and beliefs about the boundary between the living and the dead.

A very deep history of Halloween
Baked Zucchini Risotto
vegetable stock
shallot
garlic
zucchini
arborio rice
Parmesan cheese
lemon
salt and freshly ground black pepper
basil leaves
butter
Baked Zucchini Risotto
https://www.newyorker.com/magazine/2024/10/14/when-the-arctic-melts
webpage banner

When the Arctic Melts

What the fate of Greenland means for the rest of the Earth.

When the Arctic Melts
https://www.theatlantic.com/magazine/archive/2024/11/genocide-rwanda-forgiveness-reconciliation/679948/?gift=cqAGagPZVT_HCYzXnK8K2zbz-MXnjOdv2DWy6EAxRd0&utm_source=copy-link&utm_medium=social&utm_campaign=share
webpage banner

Thirty Years After the Genocide in Rwanda, Is Forgiveness Possible? - The Atlantic

Thirty years after the genocide in Rwanda, survivors and perpetrators live side by side.

Thirty Years After the Genocide in Rwanda, Is Forgiveness Possible? - The Atlantic
https://www.macchaffee.com/blog/2023/wafs/
webpage banner

Stop deploying web application firewalls

Mac's Tech Blog

Stop deploying web application firewalls
https://www.wired.com/story/what-time-is-it-on-the-moon/
webpage banner

What Time Is It on the Moon?

In 2025, astronauts will begin returning to the moon, eventually building bases and space stations, putting robotic landers and rovers to work, and mining for resources. In this bustling new era of lunar activity, they'll need to synchronize with each other. But so far there is no agreed-upon time system or zones, and there's neither GPS nor internet on the moon.

What Time Is It on the Moon?
https://www.quantamagazine.org/the-thought-experiments-that-fray-the-fabric-of-space-time-20240925/
webpage banner

The Thought Experiments That Fray the Fabric of Space-Time

Three thought experiments suggest that the space-time continuum we seem to inhabit is not fundamental but an approximation of something deeper. One shows a minimum length scale exists. Another reveals no physical property can be perfectly measured. The third highlights a mysterious property of space: its information capacity is less than expected. These experiments suggest space-time may not be fundamental.

The Thought Experiments That Fray the Fabric of Space-Time
https://alfy.blog/2024/10/19/linking-directly-to-web-page-content.html
webpage banner

Smarter than 'Ctrl+F': Linking Directly to Web Page Content

Discover how text fragments revolutionize web navigation. Learn to link directly to specific text on any web page, surpassing traditional 'Ctrl+F' searches. Explore this powerful, user-friendly feature for precise content sharing and improved web experiences.

Smarter than 'Ctrl+F': Linking Directly to Web Page Content
https://www.esa.int/Science_Exploration/Space_Science/Euclid/Zoom_into_the_first_page_of_ESA_Euclid_s_great_cosmic_atlas
webpage banner

Zoom into the first page of ESA Euclid’s great cosmic atlas

On 15 October 2024, ESA’s Euclid space mission revealed the first piece of its great map of the Universe, showing millions of stars and galaxies.

Zoom into the first page of ESA Euclid’s great cosmic atlas
https://rubinobservatory.org/
webpage banner

Rubin Observatory

The Rubin Observatory's primary goal is to conduct a decade-long scientific mission to explore some of the universe's greatest mysteries, including dark matter and dark energy. To do this, it will continuously scan the night sky for ten years, capturing more information than all previous optical telescopes combined to create an ultra-wide, ultra-high-definition time-lapse video of the cosmos. This comprehensive survey will enable the discovery of millions of new asteroids and comets, including near-Earth objects, making it a game-changer for planetary defense, while also revealing pulsating stars, distant galaxies, supernova explosions, and potentially new and unknown cosmic phenomena.

Rubin Observatory
Tokaido
Tokaido
https://castro.fm/blog/making-castros-feeds-update-faster-the-lazy-way
webpage banner

Making Castro’s Feeds Update Faster the Lazy Way

Optimizing Castro's worker jobs to get your podcasts to you more quickly

Making Castro’s Feeds Update Faster the Lazy Way
https://psyche.co/ideas/your-life-is-not-a-story-why-narrative-thinking-holds-you-back
webpage banner

Your life is not a story: why narrative thinking holds you back

Narratives help us understand the world, but they can limit our thinking and diminish our ability to live freely. They give us the illusion that the world is ordered and logical, reducing the real complexity of life. We should focus on perspectives instead of narratives to open ourselves up to other possibilities.

Your life is not a story: why narrative thinking holds you back
https://pudding.cool/2024/10/crokinole/
webpage banner

Welcome to Crokinole, the greatest game you’ve never heard of.

This isn’t just a flicking game, but a century-old test of skill and strategy.

Welcome to Crokinole, the greatest game you’ve never heard of.
https://www.npr.org/sections/goats-and-soda/2025/06/17/g-s1-72309/chess-ban-afghanistan-taliban?utm_medium=social&utm_term=nprnews&utm_source=bsky.app&utm_campaign=npr
webpage banner

The Taliban has banned a lot of things ... but chess?

A former chess coach says a member of the Taliban vice squad told him: "Playing chess is forbidden. Buying a chess set is forbidden. Even watching it — is forbidden." Why was the game banned?

The Taliban has banned a lot of things ... but chess?
https://www.eff.org/deeplinks/2024/10/salt-typhoon-hack-shows-theres-no-security-backdoor-thats-only-good-guys
webpage banner

Salt Typhoon Hack Shows There's No Security Backdoor That's Only For The "Good Guys"

The Salt Typhoon hack, which compromised U.S. telecom systems, demonstrates that backdoors intended for law enforcement access can be exploited by malicious actors, such as the Chinese government. This highlights the risks associated with mandated wiretapping capabilities and the importance of encryption by default to ensure privacy and security.

Salt Typhoon Hack Shows There's No Security Backdoor That's Only For The "Good Guys"
https://aeon.co/essays/our-crisis-is-not-loneliness-but-human-beings-becoming-invisible
webpage banner

Our crisis is not loneliness but human beings becoming invisible

The essay argues that while loneliness is a widely discussed public health issue, the more pressing and often misdiagnosed problem is "depersonalization"—a profound feeling of invisibility and not being seen or heard by others. This crisis stems from factors like the standardization of interactions in service work, the exclusion of marginalized communities, and the pervasive use of screens, which foster a culture of "watchers" and "watched". The author contends that the focus on loneliness, particularly by tech companies, serves to market AI solutions like companion chatbots, which offer a mechanized and ultimately inadequate form of "recognition". True connection, as evidenced by the experiences of gig workers, patients, and healthcare professionals, requires genuine human interaction and the willingness to truly see and understand another person, even through their imperfections. To address depersonalization, the essay advocates for human-centered solutions such as investing in quality training and staffing in caring professions, fostering inclusive communities, and critically evaluating technology based on its impact on human relationships, rather than seeking to mechanize the essential human need for genuine connection.

Our crisis is not loneliness but human beings becoming invisible
https://www.sfgate.com/sf-culture/article/california-music-festival-bubble-bursting-19786530.php
webpage banner

'We're f—ked': California's music festival bubble is bursting

The music festival industry, particularly for independent promoters, is facing a severe crisis marked by numerous cancellations and financial strain, despite initial post-pandemic optimism. This downturn is attributed to a "perfect storm" of factors, including inflation significantly increasing operational costs (e.g., portable toilets, insurance, artist fees), and a shift in consumer behavior where attendees are purchasing tickets later than usual and increasingly using payment plans, which impacts the festivals' upfront cash flow. Additionally, the market has become oversaturated with too many festivals after a boom in 2021 and 2022, leading to a decline in demand and increased competition for attendees' money. This combination of rising costs, delayed ticket sales, and market oversaturation has made it incredibly challenging for smaller, independent festivals that lack the financial reserves of larger corporations like Goldenvoice and Live Nation to survive.

'We're f—ked': California's music festival bubble is bursting
https://www.nytimes.com/2024/10/14/well/blood-sugar-levels-diabetes.html
webpage banner

Is Your Blood Sugar Too High? How Food, Sleep and Exercise Can Affect It.

The article discusses the effects of food, sleep, and exercise on blood sugar levels and provides guidance on how often to test glucose and A1C levels.

Is Your Blood Sugar Too High? How Food, Sleep and Exercise Can Affect It.
https://www.newyorker.com/magazine/2024/09/23/the-art-of-taking-it-slow
webpage banner

The Art of Taking It Slow

The article profiles Grant Petersen, the founder of Rivendell Bicycle Works, and his counter-cultural approach to cycling. Petersen advocates for "UNracing" bikes made of durable steel, designed for comfort and utility rather than speed and competition, in stark contrast to the modern industry's focus on lightweight, high-tech, performance-oriented bicycles. His philosophy emphasizes pleasurable, unhurried riding, promoting a deeper connection with the act of cycling and challenging the prevailing consumerist and competitive norms of the sport. Despite facing financial challenges and being labeled a "retro-grouch," Rivendell has cultivated a devoted following of enthusiasts who appreciate Petersen's commitment to traditional craftsmanship, his anti-establishment views, and his vision for cycling as a simple, joyful, and inclusive activity.

The Art of Taking It Slow
https://www.nytimes.com/athletic/5834953/2024/10/12/shoe-doping-marathon-times-kipchoge/
webpage banner

How ‘shoe doping’ changed marathon times forever

Technology is enabling increasingly fast times but how fair is it when it impacts marathon runners so differently?

How ‘shoe doping’ changed marathon times forever
https://cmsthomas.substack.com/p/the-atlantic-did-me-dirty
webpage banner

The Atlantic Did Me Dirty - Carrie M. Santo-Thomas

Early this summer I was interviewed by Rose Horowitch, an editor for The Atlantic. She told me that she had heard from a university professor that incoming students were struggling to keep up with the reading load. She explained that she was working on an article that would explore the problem of reading stamina and asked me to share my experiences in the high school classroom.

The Atlantic Did Me Dirty - Carrie M. Santo-Thomas
https://www.npr.org/sections/goats-and-soda/2024/10/05/g-s1-6411/electronics-public-health-waste-ghana-phones-computers
webpage banner

Here's photos of e-waste and discarded electronics in Ghana : Goats and Soda : NPR

Three photojournalists have created an in-depth report on electronic waste — its negative and ... positive ... consequences.

Here's photos of e-waste and discarded electronics in Ghana : Goats and Soda : NPR
https://mwhittaker.github.io/blog/an_illustrated_proof_of_the_cap_theorem/
webpage banner

An Illustrated Proof of the CAP Theorem

The CAP Theorem is a fundamental theorem in distributed systems that states any distributed system can have at most two of the following three properties: Consistency, Availability, Partition tolerance. This guide will summarize Gilbert and Lynch's specification and proof of the CAP Theorem with pictures!

An Illustrated Proof of the CAP Theorem
https://profmattstrassler.com/2024/10/01/why-is-the-speed-of-light-so-fast-part-1/
webpage banner

Why is the Speed of Light So Fast? (Part 1)

The speed of light is much faster, and the energy in ordinary objects far greater, than what daily life accustoms us to. Why? Step 1: new perspectives

Why is the Speed of Light So Fast? (Part 1)
https://htmx.org/essays/why-gumroad-didnt-choose-htmx/
webpage banner

htmx ~ Why Gumroad Didn't Choose htmx

Sahil Lavingia, CEO of Gumroad, explains why Gumroad chose React/Next.js over htmx for their new project, Helper. While initially optimistic about using htmx for its lightweight approach, they found it less intuitive and scalable for their complex UX needs, particularly with dynamic forms, drag-and-drop functionality, and real-time collaboration. They ultimately moved to React/Next.js for a better fit, citing better tooling, a mature ecosystem, and improved performance optimization.

htmx ~ Why Gumroad Didn't Choose htmx
https://www.theatlantic.com/magazine/archive/2024/11/the-elite-college-students-who-cant-read-books/679945/
webpage banner

The Elite College Students Who Can’t Read Books - The Atlantic

Elite college students are increasingly unable to read books due to a decline in reading habits and changes in educational practices. High schools now focus on excerpts, poetry, and news articles instead of complete books, and smartphones are also a major distraction. Many college professors are assigning less reading and lowering their expectations as a result.

The Elite College Students Who Can’t Read Books - The Atlantic
https://www.independent.co.uk/life-style/blue-zones-netflix-ignobel-prize-b2622952.html
webpage banner

Blue Zones offered hope as real-life fountains of youth – new research says they can be explained by

The article discusses the concept of "Blue Zones," regions where people supposedly live longer, and how research is debunking the claims associated with them. Dr. Saul Newman's work, which earned him an Ig Nobel Prize, reveals flaws in the data and suggests that administrative errors or pension fraud might explain the statistical anomalies. The article also highlights inconsistencies in the claimed characteristics of Blue Zones, such as Okinawa, and questions the promotion of certain lifestyle choices, like daily alcohol consumption, as healthy.

Blue Zones offered hope as real-life fountains of youth – new research says they can be explained by
https://www.nytimes.com/2024/10/02/science/fruit-fly-brain-mapped.html
webpage banner

After a Decade, Scientists Unveil Fly Brain in Stunning Detail

Scientists have mapped out how 140,000 neurons are wired in the brain of the fruit fly, Drosophila melanogaster. The wiring diagram will be a boon to researchers who have studied the nervous system of the fly species. The new fly map is “the first time we’ve had a complete map of any complex brain,” said Mala Murthy, a neurobiologist at Princeton who helped lead the effort. Other researchers said that analyzing the circuitry in the fly brain would reveal principles that apply to other species, including humans, whose brains have 86 billion neurons.

After a Decade, Scientists Unveil Fly Brain in Stunning Detail
prometheus nlbwmon metric for openwrt
-- nlbwmon.lua (Corrected nlbw command for CSV output)

-- Helper function to read /tmp/dhcp.leases
local function get_mac_to_hostname_map()
  local mac_map = {}
  local leases_file = "/tmp/dhcp.leases"
  local file = io.open(leases_file, "r")

  if not file then
    io.stderr:write("[nlbwmon_collector] ERROR: Could not open DHCP leases file: " .. leases_file .. "\n")
    return mac_map
  end

  for line in file:lines() do
    local _, mac, _, hostname, _ = line:match("^(%d+)%s+([%x:]+)%s+([%d%.]+)%s+([^%s]*)%s+([^%s]*)$")
    if mac and hostname then
      local clean_hostname = (hostname == "*" or hostname == "" or hostname == nil) and "unknown_host" or hostname
      mac_map[string.upper(mac)] = clean_hostname
    elseif mac then
      mac_map[string.upper(mac)] = mac_map[string.upper(mac)] or "unknown_host"
    end
  end
  file:close()
  return mac_map
end

-- Main scrape function
local function scrape()
  -- Define Prometheus metrics local to the scrape function
  local metric_received_bytes = metric("nlbwmon_received_bytes_total", "counter")
  local metric_transmitted_bytes = metric("nlbwmon_transmitted_bytes_total", "counter")

  local mac_host_map = get_mac_to_hostname_map()

  -- Corrected nlbw command to explicitly set comma as separator
  local cmd = "nlbw -c csv -g mac -o mac -n -q -s,"
  local handle = io.popen(cmd)

  if not handle then
    io.stderr:write("[nlbwmon_collector] ERROR: Failed to execute nlbw command: " .. cmd .. "\n")
    return -- Exit scrape if command fails
  end

  local line_num = 0
  for line in handle:lines() do
    line_num = line_num + 1

    -- This header check expects actual commas if "-s," works
    if line_num == 1 and line == "mac,conns,rx_bytes,rx_pkts,tx_bytes,tx_pkts" then
      -- io.stderr:write("[nlbwmon_collector] Correct CSV header found and skipped.\n")
    else
      if line_num == 1 then -- It wasn't the expected comma-separated header
        io.stderr:write(
        "[nlbwmon_collector] WARNING: Unexpected first line from nlbw. Expected 'mac,conns,rx_bytes,rx_pkts,tx_bytes,tx_pkts'. Got: '" ..
        line .. "'\n")
      end

      -- This regex expects comma-separated values
      local mac_addr, conns, rx_bytes_str, rx_pkts, tx_bytes_str, tx_pkts_str = line:match(
      "^([%x:]+),([^,]*),([^,]*),([^,]*),([^,]*),([^%s]*)$")

      if mac_addr then -- At least MAC was parsed (implies commas were present if further fields are needed)
        local current_mac = string.upper(mac_addr)
        local received_val = tonumber(rx_bytes_str)
        local transmitted_val = tonumber(tx_bytes_str)

        if received_val ~= nil and transmitted_val ~= nil then
          local current_host
          if current_mac == "00:00:00:00:00:00" then
            current_host = "unknown_mac_bucket"
          else
            current_host = mac_host_map[current_mac] or "unknown_host"
          end

          local labels = {
            mac = current_mac,
            host = current_host
          }
          metric_received_bytes(labels, received_val)
          metric_transmitted_bytes(labels, transmitted_val)
        else
          io.stderr:write(string.format(
          "[nlbwmon_collector] WARNING: Could not parse byte values to number for MAC: %s. RX_STR: '%s', TX_STR: '%s'. Line: %s\n",
            current_mac, tostring(rx_bytes_str), tostring(tx_bytes_str), line))
        end
      else
        -- Only log this error if it wasn't the (potentially now correctly handled) header line
        if line_num > 1 or (line_num == 1 and line ~= "mac,conns,rx_bytes,rx_pkts,tx_bytes,tx_pkts") then
          io.stderr:write("[nlbwmon_collector] WARNING: Failed to parse nlbw data line structure (expected CSV): " ..
          line .. "\n")
        end
      end
    end
  end
  local close_status, close_err_msg, close_code = handle:close()
  if not close_status then
    io.stderr:write(string.format("[nlbwmon_collector] WARNING: nlbw command close error. Msg: %s, Code: %s\n",
      tostring(close_err_msg), tostring(close_code)))
  elseif type(close_status) == "number" and close_status ~= 0 then
    io.stderr:write(string.format("[nlbwmon_collector] WARNING: nlbw command exited with non-zero status: %s\n",
      tostring(close_status)))
  end
end

-- Return the scrape function
return {
  scrape = scrape
}
prometheus nlbwmon metric for openwrt
prev next