1345 points · by sonicrocketman · 5y ago · 696 comments
One day I was working with my colleague and when the fileserver was full he went to a project folder and removed a file called balloon.txt which immediately freed up a few percent of disk space.
Turned out that we had a number of people who, as soon as the disk had some free space, created large files in order to reserve that free space for themself. About half the capacity of the fileserver was taken up by balloon.txt files.
At the end of the budget period they've only spent 80% of their allocated budget, so they throw out a bunch of perfectly good equipment/furniture/etc. and order new stuff so that their budget doesn't get cut the following year, rather than accepting that maybe they were over-budgeted to begin with.
Rinse, repeat, thus continuing the cycle of wasting X% of the budget every year.
Definite case of misaligned incentives.
Unfortunately I couldn't think of much. I suggested maybe we buy some more computers with it but I'm sure he'd already thought of that himself. I don't know what he ended up doing, but I'm sure he'd have decided to buy something with it rather than just losing it entirely.
We shot so much we destroyed some of the rifles, apparently that was better than getting a smaller allocation next year.
The non-government sector isn’t immune to this.
I see that as the SOP for large companies too...
Department either uses or loses the budget, so, there was a push to make sure nothing is left.
He told me that the school had to prevent those automatic budget cuts. His reasoning was that it's nearly impossible to get a higher budget if some big expenses had to be made. And suddenly needing a higher budge, after for example 3 years of low expenses, doesn't make a good impression on higher-level administrators.
That's the way in every major corporation I ever worked for too.
By slowly releasing supply you prevent anyone having to self-regulate (which requires unreasonable deprivation, OR global knowledge) and everyone bases their decisions off of the only global signal, free space.
More like perverse incentives.
The conventional Game Theory take is that this is a prisoners dilemma, and everyone creating balloon.txt files are defecting. They are making the most rational choice under the rules of the game (no communication thus no reliable cooperation). It's no globally optimal, but it is locally for each of them. This take also suffers from the same assumption: that rationality is centered on self-interest only.
If we are to evolve as a species, then we need to get beyond such limited thinking. We need to transcend our base natures. That is the whole point of culture: to transcend as a group what our genes otherwise program us as individuals to do.
Human selfishness IS nature. It is not just about humans either, all evolution is guided by environment (resource availability).
For anything else you need ALL people to NOT be selfish, only some being altruistic does not cut it. Your only other option is to punish selfishness, but then you will ban progress.
If most people don't create the balloon.txt file, BUT, there is no punishment for creating one, then if I believe I have a good idea and that I DESERVE more resources to pursue it, I'll create a nice big balloon.txt file. Your only option is to punish me for doing so. I would not want to live in a world where people are punished for trying to gather resources to make things that most other people won't. Some people have bright ideas, and they need resources to pursue them. Most people don't have many ideas and they don't want to do anything. If you prevent the means of passionate people to gather big resources to do big things, and want to live in a zero entropy world where everything is equal (made sure through the use of force / punishment, which will eventually be corrupt, because by definition punishers can't be equals to others) and nothing moves because of it, keep dreaming. It is not even scary because that literally cannot happen.
Refusing to accept the human nature as-is and always requiring some sort of "evolved new man" is one of the characteristics of the communist/socialist ideology.
Also a handy excuse when the system inevitably fails: it wasn't the system, it was the selfish people who did not implement it correctly.
You could make that so in this shared computing scenario, but our broader world is systemically rigged in favor of some people and against others. Capitalism depends on the un-levelness of the playing field for cheap labor.
i.e. while it can be useful if prices are attached to commodities (with caveats around externalities etc), it is not a good thing that prices are attached to humans, making some people's being and work less valued than others.
I made a bunch of 100MiB files of `/dev/random` noise (so they don't compress, compressed size was part of the quota) and emailed them to myself before the migration, to get a few GiB of quota buffer.
My co-workers were constantly having to delete old emails in Outlook to stay under quota, but not me. I'd just delete one of my jumbo attachment emails, as needed. ;)
My first full-time job had an unexplained email expiry policy. After being frustrated several times at losing some explanation on how/why, I started forwarding all my emails to gmail. In retrospect, that's probably a worse result to whoever imposed the expiration.
Fortunately, these days people are better about consolidating knowledge on wikis or some kind of shared docs instead of only email.
iirc at the time the only industries that required retention were health, legal and government
With SOX (PCI, FDIC, et al) retention laws we had another explosion of work rolling out all the compliance features of Exchange
Those were crazy times getting everybody either migrated with email or onto corporate email - there's a similar explosion of work right now with migration to M365
Email hosts love 50/100gb/unlimited mailboxes because nobody wants to migrate a bunch of giant mailboxes
A bit like when investigating police/government misconduct and a lot of files turn out to have been destroyed - but of course our data gets kept forever
I use some scripts that monitor disk space, and monitor disk usages by "subsystem" (logs, mail, services, etc) using Nagios. And as DevOps Borat says, "Disk not full unless Nagios say 'Disk is full'" :_) Although long before it is full it starts warning me.
It doesn't go off very much, but it did when I had a bunch of attacks on my web server that started core dumping and that filled up disk reasonably quickly.
Back in the day we actually put different things in different partitions so that we could partition failures but that seems out of favor with a lot of the distros these days.
This is actually kind of clever. How the tribal knowledge for how to "reserve space" was developed and disseminated would be pretty interesting to study.
To help some students had put in place a crawler making statistics about who was using the space for all classes. And usually once bitten you made your own space requisition script which would take any byte left when available until it hit some reasonable size.
It's basically reserving part of the disk for very important things only, which scares off less important uses. Like making the commons seem more polluted than it actually is to get some action taken.
If those files weren't there, the space would probably fill up, but now without any emergency relief valves.
It would be better if these files were a smaller fraction of space and had more oversight... but that's just a quota system. This is something halfway in between real quotas and full-on tragedy of the commons.
1) It's not intended to be a Real Solution(tm). It's intended to buy the admin some time to solve the Real Issue.
2) Having a failsafe on standby such as this will save an admin's butt when it's 2am and PagerDuty won't shut up, and you're just awake enough to apply a temp fix and work on it in the morning.
3) Because "FIX IT NOW OR ELSE" is a thing. Okay, sure. Null the file and then fill it with 7GB. Problem solved, for now. Everybody is happy and now I can work on the Real Problem: Bob won't stop hoarding spam.
That is all.
suppose then that you go fill up and forget to set the petcock back to normal. 8ball says: "I see a long walk in your future."
New bike has a vacuum-actuated fuel valve, no reserve. It does have a fuel gauge but since the tank is not a nice simple rectangle and the angle makes a difference the gauge is basically untrustworthy. So I go by the mileage and hope I don’t get it wrong. How hard would it be for them to add a reserve setting so it could just be between On and Reserve so I could just flip between them as needed?
If you don't have monitoring, will you even be aware that your disk is filling up?
If you do have monitoring, why are you artificially filling up your disk so that it will be at 100% more quickly instead of just setting your monitoring up to alert you when it's at $whateverItWasSetToMinusEightGB?
A second argument is it's not opened by any process. One problem I've had fixing disk full errors was figuring out which process still had a file open.
(For any POSIX noobs: the space occupied by a file is controlled by its inode. Deleting a file "unlinks" the inode from the directory, but an open filehandle counts as a link to that inode. Until all links to the inode are deleted, the OS won't release the space occupied by the file. Particularly with log files, you need to kill any processes that have it open to actually reclaim the disk space.)
There's always a big gap between what should never happen because you planned well and what does happen
And if your monitoring is working correctly, the spacer file really serves no purpose other than lowering the available disk space.
So when you're running out of space, you immediately delete the junk file. Suddenly there's "No Problem" and you've reset the symptom back to hopefully well before it was an issue. Now you can run whatever you need to, do reports, do traces etc. Even add more storage if necessary.
More importantly, as soon as you delete that junk file now you have space for logs. You have space and time for investigation.
It doesn't do that though. If you don't have monitoring/alerting that can either a) give you sufficient notice that you're trending out of disk space, b) take action on its own (e.g. defensively shutting down the machine), or c) both of the above, then having your server disks fill up is bad whether you have a ballast file or not.
If your database server goes to 100%, you can't trust your database anymore whether you could ssh in and delete an 8GB file or not.
That's it.
If you really need some reserve space (physical server), I'd much rather store it in a vg (or zfs/btrfs subvolume). Will you remember the file exists at 2am? What about the other admins on your team?
As someone who has been woken up at 2am for this exact issue, emphatically yes. I would much rather be back in bed than trying to Google the command to find large files on disk.
Hopefully if you were doing something like this it would be part of your standard incident response runsheet/checklist.
You have it mail you when it goes over 80% disk usage (and what if you are on holiday)? Does it mail all colleagues? Who picks it up (I thought Bob picked it up, but Bob thought Anne picked it up. So no one did)? Does it come and wake you in person when it reaches 92%?
Will this catch this async job that fails (but should never) in an endless loop but keeps creating 20MB json files as fast as the disk allows it to?
Is it an alerting that finds anomalies in trends? Will it be fast enough for you to come online before that job has filled the disk?
I've been doing a lot of hosting management and such. And there is one constant: all unforeseen issues are unforeseen.
I work in hosting too, and have been for a long time. I feel ya.
My org is in the middle of a SRE introduction and for some reason I'm getting a lot of pushback on the topic of 'error budgets' and what to do with alerts when they are exceeded. Can't imagine why.
https://www.dodgycoder.net/2012/02/coding-tricks-of-game-dev...
> he had put aside those two megabytes of memory early in the development cycle. He knew from experience that it was always impossible to cut content down to memory budgets, and that many projects had come close to failing because of it. So now, as a regular practice, he always put aside a nice block of memory to free up when it's really needed.
Would've been nice if someone had reserved some space ahead of time. Maybe they did, but nobody was around who remembered that codebase.
Consider how long it takes to edit or recreate art assets to reduce their size. Depending on the asset, you might be basically starting over from scratch. Rewriting code to reduce its size is likely to be an even worse option, introducing new bugs and possibly running slower to boot. At least smaller, simpler art assets are likely to render faster.
This is also the kind of problem that's more likely to occur later in the schedule, when time is even more scarce. Between these two factors (lack of time and amount of effort required to get art assets which are both decent looking and smaller), I think in practice you're actually more likely to get better quality art assets by having an artificially reduced memory budget from the outset.
1. Deal with possibly multiple issues possibly involving multiple people with the politics that entails resulting in a lot of stress for all involved as any one issue could render it a complete failure.
2. Have extra space you can decide to optimise if you want. You could even have politics and arguments over what to optimise, but if nothing happens it all still works so there is a lot less stress.
I pick 2.
Also, don't forget you're hearing decades-later retellings of someone else's story. I don't doubt that they trickled this extra space out as changing requirements mandated it, but that they kept from doing so until the team had actually reached a certain level of product-maturity and reclaimed all of their own waste first.
Remember that the PMs goal is to ship. Them blocking some assets but actually shipping is a success. Better 95% of the product than 0%.
As developers, we need to be better at handling edge cases like out of disk space, out of memory, pegged bandwidth and pegged CPU. We typically see the bug in our triage queue and think in our minds "Oh! out of disk space: Edge case. P3. Punt it to the backlog forever." This is how we get in this place where every tool in the toolbox simply stops working when there's zero disk space.
Especially on today's mobile devices, running out of disk space is common. I know people who install apps, use them, then uninstall them when they're done, in order to save space, because their filesystem is choked with thousands of pictures and videos. It's not an edge case anymore, and should not be treated as such.
Consider the hypothetical scenario of being totally out of memory. I mean completely: not a single page free, all buffers and caches flushed, everything else taken up by data that cannot be evicted. So in result, you cannot spawn a process. You cannot do any filesystem operations that would end up in allocations. You can't even get new page tables.
Hence things like Linux's OOM killer, which judiciously kills processes--not necessarily the ones you would like killed in such a situation. And again, a lot of preventative measures to not let it come that far.
Our Turing Machines still want infinite tapes, in a way.
It felt like everything was falling apart. As soon as I deleted something another app filled it up in minutes. Even Bash Tab completion breaks... There really should be a 98% disk usage threshold in Linux so that you can at least use all system tools to try and fix it.
/home still has space, though, so nothing truly breaks. Perhaps I should file a bug report about that.
"I have an unlimited data plan, I'll just store everything in the cloud." only to discover later that unlimited has an asterisk by it and a footnote that says "LOL it's still limited".
In what situation though? Let's consider disk space. This certainly does not apply to all developers or all programs. Making your program understand the fact that the system has no space left does not seem like something that would be very productive in the vast majority of cases. Like running out of memory, it is not something the program can recover from all by itself unless it knows it created temporary files somewhere that it could go and delete. If that scenario does in fact apply to your program, then it's not even an edge case: the program should be deleting temporary files if it doesn't need them anymore. If the P3 was created to add support for that exact function, then I agree that it should be acted upon. A P3 is fine as long as it's reached. If you don't reach your P3s ever, then there are different issues that need addressing. I'd even say for something littering users' disks it should be higher than a P3, but the point is it's a specific case where it makes sense to handle that error. In every other case, your best bet is a _generic_ exception handler for write operations that will catch any failure and inform the user (e.g. "[Errno 28] No space left on device"), but that's something that should already be a habit.
There are cases when you want to try to avoid running out of disk space because your program might know that it needs to consume a lot of it (e.g. installers) so it will be checked preemptively. Even then you probably do want to try to handle running out of disk space (e.g. in the unfortunate event that something else consumed the rest of your disk _after_ you preemptively calculated how much was required) so you can attempt a rollback and inform the user to try again.
Other than that, when else is that _specific_ error more important than knowing that the data just couldn't be written in general? Let's say you have a camera app that tries to save an image. Surely you'd have a generic exception handler for not being able to save the image, rather than a specific handler for "out of space", which seems oddly specific considering there are literally hundreds of specific errnos you could be encountering that would prohibit you from writing. I'm sure the user doesn't want to see something like "Looks like you're out of disk space. Do you want to try save this image in lower quality instead?"
So my point in all of this is I agree that we should _consider_ the impact of disk space but it doesn't need to be prioritized by developers unless it's actually important like in the first few examples I gave.
For example, I'm working on an NVR project. It has a SQLite database that should be placed on your SSD-based root filesystem and puts video frames on spinning disks. It's essentially a specialized DBMS. You should never touch its data except though its interface.
If you misconfigure it, it will fill the spinning disks and stall. No surprise there. The logical thing for the admin to do is stop it, go into the config tool, reduce the retention, and restart. (Eventually I'd like to be able to reconfigure a running system but for now this is fine.)
But...in an earlier version, this wouldn't work. It updates a small metadata file in each video dir on startup to help catch accidents like starting with an older version of the db than the dir or vice versa. It used to do this by writing a new metadata file and then renaming into place. This procedure would fail and you couldn't delete anything. Ugh.
I fixed it through a(nother) variation of preallocation. Now the metadata files are a fixed 512 bytes. I just overwrite them directly, assuming the filesystem/block/hardware layers offer atomic writes this size. I'm not sure this assumption is entirely true (you really can't find an authoritative list of filesystem guarantees, unfortunately), but it's more true then assuming disks never fill.
It might also not start if your root filesystem is full because it expects to be able to run SQLite transactions, which might grow the database or WAL. I'm not as concerned about this. The SQLite db is normally relatively small and you should have other options for freeing space on the root filesystem. Certainly you could keep a delete-me file around as the author does.
Also:
> On Linux servers it can be incredibly difficult for any process to succeed if the disk is full. Copy commands and even deletions can fail or take forever as memory tries to swap to a full disk and there's very little you can do to free up large chunks of space.
Why would memory swap to disk when the disk is full? I feel like the author is conflating potential memory pressure issues with disk issues.
How many serious production-grade servers even use swap, which usually just causes everything to grind to a halt if memory becomes full?
[0] https://ma.ttias.be/change-reserved-blocks-ext3-ext4-filesys...
It's also worth noting that the kernel is not a process and it does not write directly to files in the conventional sense. syslog-ng or its equivalents (which do run as root) will pick up messages from the kernel's circular ring buffer at /dev/kmsg and write them to a text file such as /var/log/kern.log, so it's possible that the kernel or one of its modules are verbose enough that syslog-ng causes that text file to get big. However, these log files can be limited to a certain size and/or logrotated[0] daily which will also remove log files older than a configured amount of time. In other words, there are better ways to manage servers than creating 8GB files as a bandaid.
"just fix the issue" often takes longer than 'rm spacer.img', which allows non-root processes to begin working immediately.
In practice, the 5% root reserve is not really an effective substitute for OP's technique.
So why would you bother making a blank file? :)
but I'll absolutely have 'rm spacer.img' memorized.
(edit: also, if you truly set -m to zero, and you fill up again, now you can't even ssh in as root...)
Except you can't ssh in as root any more. You have to ssh as a normal user then sudo in. Which may not be possible.
A paid on call admin may not mind driving to the data center too much. Everyone else would.
The only files that would be appended to on user login (by sshd, which is running as root) would be /var/log/{utmp,wtmp,btmp} to record the login (in practice I've only seen wtmp). After that you have sshd logging (e.g. /var/log/{messages,syslog,auth.log}) which is picked up by syslog-ng or its equivalents, which also run as root.
Regarding not being able to login via SSH as root by default: the sshd_config default is actually `PermitRootLogin prohibit-password` which means you can login if you use public-key cryptography, it just won't allow you to login with the root password (even if it's correct.) It's good practice these days to use public keys for SSH anyway, so I wouldn't say this is much of a setback.
As for keys, they're fine if you only ever use the same machine. Which may not happen in an emergency.
If you haven't customised this, in a pinch you can still lower it down a bit to buy some time.
> The minimum amount of space guaranteed to a dataset and its descendants. When the amount of space used is below this value, the dataset is treated as if it were taking up the amount of space specified by its reservation. Reservations are accounted for in the parent datasets' space used, and count against the parent datasets' quotas and reservations.
* https://openzfs.github.io/openzfs-docs/man/8/zfsprops.8.html
These are done on a per dataset basis (basically a directory delineated boundary).
Unlike ext[34], that reservation is not available for root's general use, but it's there.
The way I found out about it originally was because I was using external storage drives and I was never able to fit as much as I expected :D
Luckily you can easily change this without reformatting.
Nothing that actually does the "serving" or accesses data should be running as root.
The idea is that /var filling up would not make the system unrecoverable.
It's important to note that mkfs doesn't care if you are formatting the root partition or a data volume partition, it will still reserve space for the kernel.
Disk space is cheap enough that even 5% of a 14TB disk is really not that much money --- and if you see bad performance, and then have to pay $$$ to switch to an SSD, maybe it would have been much cheaper to use a HDD with a larger free space reserve....
One fun fact I learned though - one of the reasons is "for quota file". Since ext stores quota information in an ordinary file, there could be an issue where user fills up a disk but the information about it isn't written in quota file due to lack of space.
This reasoning doesn't make sense. On Linux, swap is preallocated. This is true regardless of whether you're using a swap partition or a swap file. See man swapon(8):
> The swap file implementation in the kernel expects to be able to write to the file directly, without the assistance of the filesystem. This is a problem on files with holes or on copy-on-write files on filesystems like Btrfs.
> Commands like cp(1) or truncate(1) create files with holes. These files will be rejected by swapon.
I just verified on Linux 5.8.0-48-generic (Ubuntu 20.10) / ext4 that trying to swapon a sparse file fails with "skipping - it appears to have holes".
Now, swap is horribly slow, particularly on spinning rust rather than SSD. I run my systems without any swap for that reason. But swapping shouldn't fail on a full filesystem, unless you're trying to create & swapon a new swapfile after the filesystem is filled.
I definitely agree with your advice and will go double check all my servers if /filler is 777 (not in /tmp since it's sometimes mounted tmpfs), but if sudo does break in that situation, that sounds like a pretty severe and most likely fixable bug.
Working in a terminal to find out what on earth has just filled up your disk is a real pain when your shell complains about failing to write to your $HISTFILE and such. And, of course, the problem always shows up on that one server that doesn't have ncdu installed...
I'm sure sudo can theoretically break with 0 free disk space, but that's not the usual mode of failure in my experience. At most sudo need to touch a dotfile or two, so deleting _any_ temporary file or old log archive will do for it to recover.
The balloon file is not a bad idea. I think I will apply it on my own servers just for good measure, although 8GiB is a bit much for my tastes.
These days I always at least configure an in-memory compressed swap (zram).
"The behavior is often worse without swap" is more vague / subjective. I prefer that a process die cleanly than everything slow to a crawl semi-permanently. I've previously written about swap causing the latter: https://news.ycombinator.com/item?id=13715917 To some extent the bad behavior can happen even without swap because non-locked file-backed pages get paged in slowly also, but it seems significantly worse with swap.
zram is a decent idea though. I use it on my memory-limited Raspberry Pi machines.
> Yeah that's a known problem, made worse SSD's in fact, as they are able > to keep refaulting the last remaining file pages fast enough, so there > is still apparent progress in reclaim and OOM doesn't kick in.
And so on. That's part of the reason there is a working effort towards creating a userspace OOM daemon. I'm grateful for that effort, since I'd rather have some apps crash than having my system unusable. However, there is an issue with the Linux kernel trashing.
I couldn't find mention of it in that thread, but it's mentioned multiple times in passing (as well as in the phoronix comments) that the system behaves worse without swap. It's also noted as one of the reproduction steps.
I agree that it's vague and subjective, but I'm pretty sure I've seen some serious discussion of the topic. There are a few sources that point in that direction [3-4], but I haven't seen anything conclusive.
[1]: https://www.phoronix.com/scan.php?page=news_item&px=Linux-Do...
[2]: https://lkml.org/lkml/2019/8/5/416
[3]: https://unix.stackexchange.com/a/28176
[4]: https://serverfault.com/questions/255661/linux-oom-disk-i-o-...
I recently learned searching the internets that it was the swapfile configuration. My 16GB RAM machine got a 2GB swapfile from the default installation so I doubled it to 4GB, but today it almost got full again, luckily I was just about to close a big memory hog and that saved me. I have now increased the swapfile to 6GB.
If Ubuntu is giving default installations 2GB of swapfile on 16GB of RAM, shouldn't this happen to lots of users quite frequently? How many users are technical enough to understand this and fix it? How can this be a good solution?
I can't recall that I ever got in trouble on Windows because of the swapfile.
But then you need other mechanisms monitoring "out of memory" situations. For example Kubernetes also require nodes to have swap disabled. But running workloads should have resource request/limits defined and then kubelet config specifies minimums on free disk and RAM memory. If there is not emough RAM, workloads are evicted to another worker node with more free memory automatically.
Now, my main issue is that disabling swap doesn't cause this. With swap, OOM ends up being detected and corrected by the kernel. On some machines, it doesn't happen without swap, and often neither with swap. A sweet spot seems to be current-to-last CPU gen with 8 GB of memory.
There's probably a lot of factors at play: what makes a task "hung"? How memory pressure is measured. Stuff probably changed with time, SSDs are now pretty quick, yet storage is a lot slower than RAM compared to what it used to be.
Anyway, I use zram and have upgraded my memory, I'll also increase a bit my swap partition size in light of all of this. I'll probably have a look at userspace OOM daemons too.
Kernel panic? some user process you deem essential stopping?
About the blogpost itself:
The disk filled up, and that's one thing you don't want on a Linux server—or a Mac for that matter. When the disk is full nothing good happens.
I had this happen few times on a Mac and every time I was shocked that if disk gets full you cannot even delete a file and the only option is to do a full system reboot. I was also unable to save any open file, even to external disk and suffered minor data loss every time due to that.
What is the proper way of dealing with such issue on macOS? (or other systems, if they behave the same way)
This just happened to me. I got the best error message I've ever seen. Something akin to "Can not remove file because the disk is full." This wasn't from the Finder, this was command line rm.
On the Mac it's also exacerbated by the fact that swap will use the system drive and can fill up the disk, and can not be stopped. If you have some rogue process consuming RAM, among other things, your disk will suffer until it is full. And, as mentioned, macOS does not behave well with a full disk.
And, even if you've remedied the swap issue (i.e. killed the process), there's no way I know to recover the swap files created without restarting.
Just seems like the design is trouble waiting to happen, and it has happened to me.
When this last happened, somehow it managed to corrupt my external Time Machine volume.
One way to buy yourself some time is to disable the sleep file. I'm not sure what it's called -- it's a file that MacOS uses to let the computer hibernate when there's no power. It's a few GB, which (like the blog post stated) is a nontrivial amount of freeable space.
Should be /var/vm/sleepimage and the same size as your RAM.
Fun story with this. Ubuntu now has an experimental root-on-zfs feature. I installed it and started playing with some docker containers, trying to compile a certain version of pytorch. Suddenly, my computer crashed. Apparently, my root partition filled because docker installed everything on the same partition as my OS, crashing everything immediately.
As long as your application does not have root privileges, it will hit the wall when the free+reserved space runs out. Instead of the clumsy "spacer.img" solution, one could simply (temporarily) reduce the reserved space to quickly recover from a disk full condition.
“To discourage casual use of this advanced feature, there is no English long name for this variable.”
But the language-build flag to enable it has a great name: -DPERL_EMERGENCY_SBRK, obviously inspired by emergency brake.
1. Checks that all domains can be accessed via HTTP and HTTPS. If not, DNS might have died.
2. Checks that a few known CMS-generated pages contain some phrases they should contain. If not, SQL might have died.
3. Checks that the HTTPS certificate has enough runway left. If not, certbot might have died.
4. Sends a basic email message from my domain to a gmail account. Receives it via IMAP and sends a reply. Then, verifies the reply. This catches a whole bunch of mail-related issues.
5. Checks the free RAM and disk space. Updates an internal "dashboard" page and sends me an email if they are off.
It only took a couple of hours to hack this together and I must say, I get a much better night time sleep ever since.
This is a low cost way to make failure of your first line of defense less painful to recover, and seems like a Good Idea for those managing bare-metal non-cattle systems.
Was also thinking of customising the login greeting to mention the file (/etc/motd).
I guess a big file is not a bad idea either.
dd if=/dev/zero of=deleteme.file bs=1M count=8196
...the "free space" shown by "df" slowly decreased while the file was being created, but then once the operation completed that "free space" magically went back to its original value => the big existing file (full of "0"s) was basically not using any storage.Is this what you mean?
I just tried to replicate this behaviour but, dammit, I cannot demonstrate that right now as the behaviour so far was the expected one (free storage decreasing when creating the file and sticking to that even after the completion of the operation).
I strongly believe that that's what I saw in the past (when I was preallocating image files to then be used by KVM VMs), but now I'm wondering if I'm imagining things... :P
EDIT: this happened when using ext4 and/or xfs (don't remember) without using any compression.
dd if=/dev/zero of=a_sparse_file bs=1 count=0 seek=8G tune2fs -m 2 /dev/hda1
That sets the root reserve on a disk. It's space that only root can use, but also you can change it on the fly. So if you run out of userland space you can make it smaller, and if a process running as root fill your disk, well, you probably did something real bad anyway. :)But yeah, this is a pretty good hack.
On the other hand, if your monitoring was set up well, you got a notification and had time to react to it before it was at 100%.
Granted, if you have a process that just wrote a file at maximum speed, that time window is tiny, but that's not usually what happens in my experience. What happens is that something starts logging more and it slowly builds up while you're happy that your server is running so well that you don't need to pay attention. And then the alert comes and tells you that there's less than 10% space available, and you have plenty of time to investigate and avert the crisis.
You solve the issue right then and there. Step 1. realize there is a space issue and get to terminal Step 2. free space so any solution has memory Step 3. Solve by doing <??? specifics ???>
Once the project invariably goes over budget, he drops the plans for the gold and frees up extra funds.
Edit: I think it was a large marble slab. Same thing.
/var is usually where the most data gets added. Logs, database files, caches, and whatever other junk your app spits out. 99% of the time that's what causes the out of space issues. By keeping that separate from root, you've saved your system from being completely hosed when it fills up (which it will).
Obviously there are other places that should get their own mounts, like /home and /usr, but before you know it you've got an OpenBSD install on your hands with 15 partitions :)
https://man.openbsd.org/disklabel#AUTOMATIC_DISK_ALLOCATION
At least put /tmp in its own partition as well.
Multiple partitions can also save a lot of recovery time when there is a multiple bad sector event that corrupts an entire partition beyond recovery.
/usr isn't a bad choice, either.
:)
Hopefully docker will lose the fight for mindshare in the ML space.
It's the same as old VW beetles which had a reserve gas tank. When you ran out of gas you opened a valve and you could limp to a gas station. Less likely to fail versus a 1950's era gauge that is telling you you're low. Also impossible to ignore it.
In scuba diving there used to be "J-valves". When you had 50 bar left in the tank they would cut out. Then you would pull to reenable your air and return to the surface. Unsurprisingly they are no longer popular.
It's not that straightforward IMO. Would this file be deleted before the space is filled? If so, there is alerting in place, and it assumes there's a way to delete files before space fills up. If this file is deleted after space fills up, how is this different from not having the file, other than making finding files to delete easier? Then what happens after that? If you delete the file and realize there's nothing else to delete, you'd have to solve the problem the same way if you didn't use this method.
What if the solution required some amount of free space? (eg. installing a package or swap)
Perhaps consolidate/defrag once a year. Even monitoring total usage more often than that is probably not worth the effort - just buy ample cheap storage.
Also, there was a tradition to split drives into OS, DB, DB Logs. That was mostly a rust performance thing and these days is probably just voluntary management overhead.
RAM is another story.
> "just buy ample cheap storage"; "That was mostly a rust performance thing and these days is probably just"
In the UK a 6TB enterprise rust disk is £150 and a 2TB enterprise SSD is £300, it's 6x the price to SSD everything, and take 3x more drive bays so add more for that. And you can never "just" buy more storage than you ever need - apart from the obvious "when you bought it, you thought you were buying enough, because if you thought you needed more you would have bought more", so that amounts to saying "just know the future better", but it can't happen because Parkinson's Law ("work expands so as to fill the time available for its completion") applies to storage, the more there is available, the more things appear to fill it up.
Room for a test restore of the backups in that space. Room for a clone of the database to do some testing. Room for a trial of a new product. Room for a copy of all the installers and packagers for convenience. Room for a massive central logging server there. What do you mean it's full?
> This is 2021 and the technology is from the 90s I don't see how this is a valid point. Is integrated circuit technology outdated because it was developed in the 60s?
I'll take lvm/zfs/btrfs subvolumes over static partitions any day.
Also one of the main reasons server disks go full is generally log files. Always remember to "logrotate" your log files and you will not have this issue that much.
Yes one more thing, for all user uploaded files use external storage like NFS or S3.
We send our log files to S3 too. I mean, we write them locally (EC2) and then push them to S3 every minute.
Then we have a tool that will let us search the log files in S3 and it will parse these rotated log files and join together the relevant pieces depending on what we're looking for (or all of it for a specific time period if we don't know what we're looking for).
This is great because if the server goes down and we can't access it, or the instance is gone, we can still see log files from shortly before the problem occured. We also use bugsnag, etc for real time logging and tracking where possible.
Most uncontrolled space usage comes from logs, users doing user things, or something like build servers just eating temporary and caching storage for lunch. Databases also tend to have uncontrolled space usage, but that tends to be wanted.
So, if you push /var/log to it's own 20-30Gb partition, a mad logger cannot fill up /. It can kill logging, but no logging is better than fighting with a full /. Similar things with /home - let users fill up their home dirs and pout and scream about it... but / is still fine. And you can use their input to provide more storage, if they have useful workflows.
Something like databases - where their primary use case is to grow - need monitoring though to add storage as necessary.
Because really the biggest problem when I've had a partition get full, is I sometimes can't even delete the offending log file.
If y'ask me, that's a fundamental design flaw. Of course nobody asked me...
Tons of recordings from back in the day.
You can run into real trouble on btrfs if you fill it, it has no reserve space to protected from this scenario. ZFS at least reserves a fraction of the total space so that deletes are allowed to work even when the pool reaches 100% capacity.
By default, only root can use the last 5% of disk space.
That means you can fire up a root shell and know you have a buffer of free space to resolve the issue.
some reading if LVM is new and you want to know more: https://opensource.com/business/16/9/linux-users-guide-lvm
edit to add: pv=physical volume, vg=volume group, lv=logical volume
1. Tunefs
2. spacer.8gb
3. lvmYou'd effectively send all block changes through LVM twice (once through the file, then through the underlying block device(s))
For block operations it's no different from manual setup of loop-mounted volumes, that also need to travel a couple of layers to hit the backing device.
Though there is an important caveat - LVM is more abstracted, making it easier to mistakenly map a drive onto itself, which may create a spectacular failure (haven't tried).
IIRC 5% is reserved when the filesystem os created, and if it gets full you can run:
tune2fs -m 4 /dev/whatever
which will instantly make 1% of the disk available.
of course should be used sparingly and restored when finished
Basically it lets you knock 8 GB or more (although it's a percentage instead, 5% by default) off of the disk space available to non-root users.
When it hits 100% and things start breaking, that reserve can be used by root to do compression safely, move things around, and so on. Alternatively the reserve percentage can be changed with a single command (by root), to allow non-root processes more space while the admin contemplates what do do next.
One nice aspect of using the reserve instead of a file is that it prevents runs of "du" for including the file in their results. Another is that it's pretty much impossible to accidentally remove the reserve (or for some other admin to find it and decide it's superfluous).
This is less effective at sites that have a lot of services running as root, in which case only your approach is fully effective. I want to say "But who does that nowadays...", but it happens.
tune2fs apparently also supports allowing members of a certain unix group or user to have access instead of solely root.
The core command for all this is:
tune2fs -m <reserved-percent> <device>
One other thing you might want to worry about: inode exhaustion. tune2fs has an inode reserve % as well - and trying to emulate this by creating a few hundred thousand files instead would be... inelegant. # rm -f /mnt/data/zero.*.fill
rm: cannot remove '/mnt/data/zero.1.fill': No space left on deviceThey do. In my experience, the only disruption to most terminal operations is that tab completion will fail with an error.
> Copy commands and even deletions can fail
I've had that happen too many times, so I don't know why would fill up my disk with a hacky spacer file, which surely can also fail to be deleted when the disk is already full.
So I wrote an on-disk cache system that would monitor disk usage, and start to evict and shrink its disk space usage. It would take up to N gigabytes of disk (configurable) for the purpose of caching, and maintain an M gigabytes free-disk-space buffer.
Say you had a 100 GiB total space on a partition, with 8 GiB used for cache with a 2 GiB headroom. As legitimate/regular (customer) space usage increased and reached 91 GiB, the cache would see 9 GiB available, and removing the 2 GiB buffer, would start to evict items to resize to 7 GiB, and so on until it had evicted everything.
When this system deployed, it started to trigger low-disk-space alerts earlier than before. At first that seemed like a problem, but the outcome is that we were now getting low-disk-space alerts with more advance warning, and the cache bought some time as it kept resizing down to free up space. It kind of, in a way, served the same purpose as described in this blog post.
Overall this cache was pretty neat and still is, I bet. There's probably ways to do similar things with fancy filesystems (or obscure features) but this was a quick thing to deploy across all servers without having to change any system setting or change the filesystem.
I sometime wish I had done this in open-source, because it would be convenient to use locally on my laptop, or on many servers.
It looks to you like everything is there, but in reality it downloads as you click on things, and empties cache if the free space begins to drop below a set amount.
i do wonder how many FS would actually allocate the 8GB if you, for example, opened a file, seeked to 8GB mark, and wrote a character. many file systems support "sparse files"[1]. for example on btrfs, i can run 'dd if=/dev/zero of=example.sparse count=1 seek=2000000' to make a "1GB" file that has just one byte in it. btrfs will only allocate a very small amount in this case, some meta-data to record an "extent", and a page of data.
i was expecting this article to be about a rude-and-crude overprovisioning method[2], but couldn't guess how it was going to work. SSDs notably perform much much better when they have some empty space to make shuffling data around easier. leaving a couple GB for the drive to do whatever can be a colossal performance improvement, versus a full drive, where every operation has to scrounge around to find some free space. i wasn't sure how the author was going to make an empty file that could have this effect. but that's not what was going on here.
[1] https://wiki.archlinux.org/index.php/sparse_file
[2] https://superuser.com/questions/944913/over-provisioning-an-...
This is true. If you are replicating this, copy from /dev/urandom rather than using an empty file.
In some game studio, as a project neared its release, the team was still struggling with memory issues. No matter what they did, they had a surplus of just about 2MB. The artists have reduced their polygon counts drastically, the programmers have checked every possible leak, have optimized algorithms and buffers the best they could but the 2MB surplus just kept haunting them.
That's when the VP of Engineering stepped-in. Calling the TL of the project into a closed-doors optimization code-review, they had the source code on a large screen and the TL talked the VP through everything the team has done so far to stay within the memory budget.
As the TL finished the walkthrough, the VP opens some mother-of-all files and deletes a cryptic variable declaration to the effect of:
int toLiveBuffer[2000000];
The VP then explains that he hid this declaration in their codebase after a project that had to optimize drastically late into the development cycle. But first he wanted to make sure that the team did their homework.And poof. They emerge from the closed-doors meeting jubilant and victorious. The game is ready for prime time!
I'm not going to try to understand the logic as to why APFS requires free space in order to delete files (via any method, including dd)
They work by appending to the log then compacting sometime later, not modifying things in-place. As such, you always need a reasonable supply of free blocks so this can occur.
> in a moment of full-disk crisis I can simply delete it and buy myself some critical time to debug and fix the problem
Uhh...
I don't understand this. Swap is either a swap partition, or a specific swap file, all of which allocated in advance, so the fullness of the storage should have no bearing.
I found a bug with time machine where it wouldn't delete local copies properly and filled my hard drive until I couldn't do anything. The OS slowly stopped working. At first I couldn't copy or save anything, then deleting files made more files. It was so bad that the `rm` command eventually wouldn't work from recovery or the local OS. I could do nothing. I had to format.
It happened again and I learned to manually delete the time machine local snapshots, but it was crazy how hard it was to recover once it took all my storage. That bug is fixed now.
With physical servers it might be a different story and might be a good idea. I tend to size filesystems to the requirements I have and enlarge them when required (it gives you a periodic reminder to think about what waste you have accumulated). That way, I can still add space even if the filesystem has been filled up. However, if you do it just to have some space when you need it, it probably is overkill and to have an empty buffer file is a lot easier to handle.
Will be switching to this hack! Perfect illustration of the KISS principle (Keep it simple, stupid).
> I can see how sometimes, when you're up against the wall, having a bit of memory tucked away for a rainy day can really make a difference. Funny how time and experience changes everything.
[1] https://www.gamasutra.com/view/feature/132500/dirty_coding_t...
The preallocated buffer was essential. Without it typical result was recursive out-of-memory that eventually deadlocked/crashed the VM with no recovery.
Recently, I extracted a large archive with Linux on the ntfs, and the partition was full
Then Windows did not start anymore
Linux would only mount the partition as read-only, because it was marked dirty after the failed start. Finally I found a tool to reset the mark, and delete the files.
Now Windows starts again, but my user account is broken. It always says "Your Start menu isn't working. We'll try to fix it the next time you sign in.", then I sign out, and it is still broken
I had to make a new user account
Even disconnecting the disk technically doesn't break the OS. Because of the "Windows To Go" feature, the OS can detects this and pauses.
(Note: Windows To Go is officially removed from current versions but the code that freezes is still there. However, whether that works with your hardware is basically a gambling... so yeah dont try at home/work.)
in_case_of_fire_break_glass.binAlso I keep databases on their own partition so that nothing else can accidentally fill up the space and lead to data loss.
I think the ideal ideal is tuning the reserved blocks in your filesystem.
xfs_io -x -c 'resblks ...> On Linux servers it can be incredibly difficult for any process to succeed if the disk is full.
You won't feel too clever if you come to grow your LVM volume into the free space and it won't work because there's no free space on the filesystem! :)
(I don't actually know if this would fail or not - but the point is "rm spacer.img" is pretty much guaranteed not to fail).
The service in question didn't require high availability (it was a mailing list processing/interface thing, if I remember correctly) but it had some memory leak which would eventually devour all the memory in the server, in about 2 days.
This hack served its purpose well, until the service was eventually replaced by something else.
It seems like you have sort of done that, but in this case you are actually allowing your system to get into a bad state before you react.
Perhaps it’s better to be proactive instead of reactive.
Due to the simplicity of this solution, there's not much that can go wrong.... unless you can't actually access the server anymore to delete the file...
I see this more as a second line of defence
https://blog.urbackup.org/371/ransomware-canary
https://support.huntress.io/article/136-ransomware-canaries-...
- Why do you carry a phone booth around? - Oh, you see, it's for the lions. If I see a lion, I drop the booth, step inside and I'm safe. What's with the anvil? - It's for the lions too. If I see a lion, I drop the anvil and I can run way faster!
Good trick anyway!
Such flexibility has been invaluable over the years. Thankfully with block storage and modern operating systems/file systems growing volumes can be significantly easier for most servers.
If the disk would ever fill up:
1. Buy an additional virtual disk
2. Add the disk to the LVM volume group
3. Expand the Logical volume
A really good primer on LVM:Guess this is another place of differentiation that some of these platforms could offer.
> save_my_butt.img
and now it's 0 bytes.
> filename
didn't null it, then just
echo "0" > filename
However on a sketchy drive this is obviously not a wise move.
Actually wait, NFS2/3/4 has reserved block counts you can free.
# tune2fs -m 3 /dev/md2
# Setting reserved blocks percentage to 2%The better solution is simple monitoring. Alert when limit is passed. Increase limit to 16gb disk space remaining if paranoid.
This technique even has a name : ballast file
When the drive fills and everything breaks and, you /have/ to respond, and it becomes socially ok to make it your highest priority and drop everything. An email "only a few weeks until maybe it runs out of space" is much harder to prioritise and get anyone to care. With this system, the time when it fills and breaks has some flex for you to not go down with the server, and save your own bacon. It's as much a fix for the organization as anything else.
I see this most in smaller company aging systems where they had ample storage and drives for a few years ago when they were new, now they're crammed full with the growth of software, libraries, updates, data, new services being deployed on them, increased demands, and nobody wants to commit to more storage for an older system towards the end of its warranties, but they definitely don't want to commit to the much larger cost of a replacement and all the project work, and running at 90% full costs nothing and involves no decisions. 91%. 92%.
That's only a problem if your memory is full as well, and even then, I've never encountered a server that uses a swapfile instead of a swap partition.
On Linux, this is not necessarily the case, as you can change the file on disk while the executable is running. I don't know if Linux just keeps executable code in memory all the time, or if it is smart enough to detect whether a copy of executable pages still lives on disk.
What you can do is delete and then recreate the executable. Then the deleted data simply sticks around on disk until it's no longer referenced
This can be adjusted with tune2fs -m <percentage> /dev/sda1
You can check the reserved blocks with sudo tune2fs -l /dev/sda1 | grep 'Reserved block count'
To me it has a taste of domain squatting or GPU scalping, but you don't do it with strangers, but your team.
Iirc some filesystems allow you to reserve a percentage of blocks for this particular use case (recovery by root).
Ext2/3 for sure, ext4 probably too.
Not sure you can do that on linode on the rootfs, since the filesystem is mounted, tho.
I really wish they would move it from a sparse memmap() file to a btree or something.
Usually when free space is exhausted, it's for non-root users. You get that same "time to fix stuff by deleting the file" by using tunefs to change that root reserved space to zero.
Plus have /var/log on a separate file system and make sure that your log rotations are based on size as well as time.
I have been there a couple of times and it is a land of crazy unpredictable behavior.
Setup quotas or implement some damn monitoring -- if you're not monitoring something as simple and critical as disk usage, what else are you not monitoring?
Quotas are tricky to set up when things are sharing disk space, and that could easily give you a false positive where a service unnecessarily runs out of space.
Can't you put disk size monitoring?
Regards, Hitul Mistry digiqt.com
Not only did it give us a "big red button" to press during emergencies like OP, but it revealed important logical scaling issues before they became real problems.
[1]: tldr; 1 million people playing a single game of Pokemon Red by using chat to send button presses
Been doing this since the UFS days
With a "ballast file" (as another commenter termed it), you can decide exactly when processes get to start consuming disk again, and that can give you some headroom to fix the problem.