HTPP Accept-Language request header to ResourceBundle

HTTP Accept-Language header is specified by the client to inform the backend what the preferred language for the response is. In Java, the go-to utility for handling localization is ResourceBundle.

What is missing is a standard way to properly convert the input header to the correct ResourceBundle. Specifically,

is insufficient. HttpServletRequest::getLocale() method returns the top preferred locale but if no such ResourceBundle exists, it will fall back to default locale instead of going down the priority list. For example, this header:

Accept-Language: de-DE;q=1.0,fr-FR;q=0.9,en-GB;q=0.8

when backend is missing de-DE translations will return the system default (e.g. en-GB) instead of fr-FR which is the second by priority.

Clients don’t usually request languages unknown to backend but it is possible in theory and languages can be automatically added by the client platform (iOS does this) without the client knowing.

We need to iterate the locale chain and find the highest match that exists as a bundle.

Below is a sample in JAX-RS environment.

 

Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs

resize Fedora root partition

Default root partition size on my Fedora installs usually becomes too small down the line to the point I can no longer install packages or perform the upgrades without removing packages or clearing dnf cache.

Therefore I wanted to shrink my home partition and add that space to root.

We can’t perform the resize while partitions are mounted so we need to boot in emergency or rescue mode. I first tried the emergency mode but the boot would lock up at Fedora logo so I decided to go with rescue instead.

Once in grub menu, press e to edit. At the end of the line of linux16 or linuxefi entry, add

systemd.unit=rescue.target

Press Ctrl+x to boot with modified parameters. Once in rescue mode, perform the resize:

lvresize -L -10G --resizefs /dev/fedora/home
lvresize -L +10G --resizefs /dev/fedora/root


Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs

That moment when you need to look up definition of C++ for loop

I was getting a segfault on an old piece of code which I maintain. The culprit was pinpointed to this:


I went through this piece if code at least 10 times without noticing the problem. The snippet is simple enough.. when match is found, set found to true and that breaks the loop since loop condition now evaluates to false. The iterator remains at the position of matched element.

WRONG.

What we are actually getting is iterator+1.

What we don’t see directly from the code is that increment happens before the condition is evaluated for the next loop, giving us iterator+1 which causes a segfault if match is found on last element.

Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs

Tenant resource authorization in JAX-RS

You have a book REST resource and each book has an owner. Only the owner of the book can access an owned book. JAX-RS specification has no answer to this problem since it only provides a role based security with @RolesAllowed annotation. It is unfortunate JavaEE spec does not offer at last some interfaces which we could then imlement for this purpose.. we need to roll our own. There are many ways this can be achieved, I will present one way of doing it.

Owned JPA entities extend a common class

All owned entities should extend a common class, let’s call it OwnedEntity.

Protect owned resources with an interceptor

Create an interceptor which we will use on each owned resource that will check the owner of the entity against the authorized user. We pass the owned entity as a parameter. We will need this information to be able to fetch the correct JPA entity in the interceptor implementation.

We protect an owned resource with this interceptor

Interceptor implementation

Make sure the priority of this interceptor is lower than your security interceptor, since a valid authenticated user should already be present before it.

The limitation of this interceptor is that it can only protect ID based resources of type /resource/:id. For list resources, use seperate logic to insert an additional WHERE filter by owner ID to TypedQuery/Criteria query used for list fetching.

Second limitation is that the entity ID should always be declared first in resource method. Another way would be to enforce the name “id” as the parameter name representing the entity ID, but this requires additional reflection info to get method parameter names.

The example here uses SecurityContext to retreive the authorized user. You might need to inject your own context or parsed JWT token to retreive the needed identificator, depending on what you store in your database as owner ID (user UUID, email etc).

An improvement of this interceptor is to check the roles in security context and skip the owner check if role is an ADMIN or similar, since we probably want to allow admins to access all resources.

So how useful is this?

Good:

+protects owned resources with a simple annotation

Not so good:

-only protects ID based resources, you still need a seperate mechanism for lists
-only protects the base entity, not nested owned relations (/book/:id/somethingElse/:id2), which would mean child entity can have different owner than parent and client must be prevented from access of the child. I did not yet stumble upon such a requirement though.
-forcing method parameter position or consistent naming in resource methods Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs

Creating a new torrent and seeding with Transmission

You have setup a Transmission server on your Linux box together with Transmisison Web or something along those lines and now you are wondering.. how can I actually seed a NEW file?

I couldn’t find a straightforward answer on the web so here is the short tutorial:

  1. Upload your file to your transmission download directory
  2. cd to that directory and create a torrent file (lets say the file you uploaded was called  myfile.rar):

    Replace tracker1, tracker3, tracker3, …trackerN with a bunch of trackers. Better specify more than one in case they go down. Here is a cool little list of public trackers.
  3. Download the new .torrent file you just created, open Transmission Web and add the torrent. Since the file already exists in download directory, Transmisison will just revalidate the data and start seeding. *mind blown*
  4. Distribute the torrent file to your people or generate a magnet link with

     

Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs

Ubuntu 18.04 on MacBook Pro 11.5 – a sad state of affairs

There was an extra MacBook Pro 11.5 lurking around so I decided to install Ubuntu 18.04 on it and try to setup a usable workstation.

A culmination of several issues prompted me to not pursue this setup further. Linux drivers and MacBook hardware just don’t play along very well.

Display flickering/corruption on main display

The bottom part of the HiDPI screen is experiencing some kind of flickering as tracked by this bug. Changing desktop environment, distros and X server configuration did not result in any improvements. For a moment Wayland seemed to have solved the issue only to reappear on next boot.

Since I also connected 3 external monitors this was not a deal breaker. External monitors did not display this issue.

Fan going at 100% most of the time

Even at idle or low load the fans would spin at 100%. Thermald was not doing it’s job for whatever reason. It is hard to say why since most temperature sensors seem to be working fine and report acceptable temperatures.

I found a simple but great project called mbpfan which stopped the fans immediately after being started and still kept temperatures seemingly in check. I increased the minimum fan speed in mbpfan config just to avoid any potential overheating problems. With this setup I was getting 70-80 degrees with no overheating problems and a quiet fan.

CPU is in constant low frequency state (dealbreaker)

After installing cpufreq gnome extension I figured out that CPU is always at 800MHz. Mbpfan was not the cause since the same lack of scaling appeared when it was turned off.

First I tried to disable Intel p_state driver but the lack of scaling continued. Using userspace driver in cpufreq, I was unable to change min/max frequencies or force a specific frequency via cpupower.

As per ArchWiki, I gifured out that BIOS was enforcing this state via

After ignoring ppc via

the CPU instantly started to scale as expected. Unfortunately this was not the final solution since the low state  would randomly reappear again for long periods of time with small time windows of scaling working as expected. Therefore, even with ignore_ppc I would still get 800MHz most of the time with temps reported around 70 degrees.

In this state Gnome Shell would lag and everything was half-usable.

Something in hardware was throttling CPU and I wasn’t able to overcome it.

Bcmwl driver very spotty

WiFi bcmwl driver is very spotty. It would connect to Android hotspot no problem but it failed to connect to WiFi router. Small sample of 50% reliability.

Display positions not remembered after reboot

I had to rearrange the external monitors on each reboot since Gnome would not remember their positions. I had to come up with xrandr script to run after login to remedy this sad state of affairs.

No per-monitor scaling

Gnome still does not support setting the scale factors per monitor. Again, I had to come up with xrandr script to achieve 200% scaling on HiDPI and regular scaling on external monitors (1900×1200).

Broken scaling under Wayland

Apparently if you set the scale factor to default in Wayland session, things should “just work” across HiDPI and non-HiDPI displays. Don’t believe these people, they are liars.

I set the scaling to default but that made HiDPI desktop tiny while external monitors were fine. Increasing the scaling to 200% made HiDPI fine while external monitors scaled also.

There is also no xrandr under Wayland so you can’t help yourself with that.

Broken rendering of electron apps on external monitors

If using Postman on an external monitor, parts of the dialog boxes would simply disappear, making the tool unusable. Using Postman on main display did not have this issue. Weird.

 

The bottom line: get a Dell or a Lenovo for your Linux workstation needs. Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs

Xrandr framebuffer and per-display scaling

Ubuntu 18.04 LTS came out recently with Gnome desktop as default. Unfortunately even in 2018, it won’t remember the external monitor positioning after reboot and has no support in display settings to set per-display scaling. Year of the Linux desktop, anyone?

Xrandr is a powerful Linux tool to manipulate displays. Unfortunately, the man page is very sparse on information with badly explained flags and various Linux guides are no better.

This example will create a triple monitor setup with HiDPI laptop display at the bottom of the array.

Xrandr command:

 

Gnome scaling is set to 200% so our HiDPI native display looks normal. Unfortunately this also means non-HiDPI displays have this scaling applied which is not what we want.

Framebuffer is the full outer rectangle which must be able to contain our display setup as a whole.

Since external displays are scaled 2×2 (zoom out), they take twice the size of their actual resolution in our framebuffer. Meaning their sizes in fb are actually 3840×2400.

Y of the framebuffer is therefore 2400+1800=4200 (HiDPI display is scaled 1×1 so it takes the same amount of space in the framebuffer as it’s resolution).

X of the framebuffer is 3*3840=11520.

–fbmm specifies the full framebuffer size

–pos specifies the position of the display in the buffer. 0x0 position starts on top-left corner.

–mode sets the actual display resolution

–output specifies the display output (run xrandr to list all available)

–scale specifies “zooming” in (<1) or out (>1)

 

The end result has some invisible area on the bottom-left and bottom-right corners so it is not ideal. I have yet to figure out if it is possible to specify fencing around that area.

The HiDPI display is also not perfectly aligned with the top display but that could be corrected with fractional scaling. It didn’t really bother me to fiddle with that.

Finally, you should run this command with a startup script so you get the correct monitor positioning and scaling after login. Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs

Running multiple PHP versions and compiling from source

We had a peculiar situation where both PHP5 and PHP7 were needed at the same time on a FreeBSD server. It was also prohibitive to get root or sudo access on the managing account. The solution was to compile PHP from source with fpm, run fpm on a UNIX socket and wire the specific domain which needed PHP7 through Nginx.

Compiling from source

Compiling PHP is pretty straightforward but you can easily forget crucial configure flags. First get the source archive. After trial and error, this appears to be “good enough” for Laravel 5.6 requirements.

Followed by

copy php.ini-development file from source to the –with-config-file-path directory and call it php.ini.  In PREFIX/bin confirm that php binary is loading your ini file by running

If you made a mistake in your configure run, you have to make clean first or the changed options won’t be picked up.

Configuring fpm

In your PREFIX/etc folder, check php-fpm.conf. The only lines I bothered to verify and edit were pid, error_log and include, the rest can be left as is.

Inside folder php-fpm.d create a config file like my.subdomain.conf and add something like

You can study fpm config in great details but this is enough to get you going.

Now you can run your PHP7 fpm process in PREFIX/sbin with

Since we don’t have any init scripts in this case, we must be able to kill it also. Find it with

and kill with

Make sure it says php-fpm: master process in the ps output, killing children doesn’t do anything, just respawns them.

Now you just need to wire up your Nginx to use this fpm instead of the PHP5 system one by specifying

We now have PHP dualstack with some web apps running on system provided PHP5 and some on our own built PHP7. We did not need root for this process, except possibly for configuring Nginx.

One obvious downside is that you now have to take care of updating your PHP version on your own but that is one view we had to sacrifice. Updates should be relatively easy and fast since make install won’t remove your config files in existing installation and compiling PHP takes just a few minutes.

  Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs

Centos Docker unable to unmount on stop/start

Error looks something like

Error response from daemon: driver “overlay” failed to remove root filesystem for 805c245dad451542b44bb1b58c60887fa98a64a61f2f0b8de32fa5b13ccc8ce4: remove /var/lib/docker/overlay/8f666b802f418f4a3dc4a6cafbefa79afc81491a5cb23da8084dd14e33afbea0/merged: device or resource busy

It usually appears when stopping and starting a container. It results in Docker container not being able to start or starts in a weird dead/removed state. Issue is presumably fixed in Centos 7.4 as per this github issue, but a workaround exists:

1. Grep by part of ID:

it shows which process is holding up the mount in busy state

/proc/31415/mountinfo:…

2. Kill the process

  Cen
GitHub
Eurobattle.net
Lagabuse.com
Bnetdocs