#StackBounty: #20.04 #power-management #shutdown #hibernate How to disable the behaviour of the power button on Ubuntu 20LTS

Bounty: 100

I disabled the power button on my desktop (pressing it did nothing, no shutdown, no hibernation/sleep, because my kids like it to press)
After I upgraded my ubuntu from 18LTS to 20LTS, the disabled power button behaviour does not work anymore. When it is pressed, it hibernates the PC.

Here are my current settings gsettings list-recursively org.gnome.settings-daemon.plugins.power

org.gnome.settings-daemon.plugins.power lid-close-ac-action 'suspend'
org.gnome.settings-daemon.plugins.power time-critical 300
org.gnome.settings-daemon.plugins.power power-button-action 'nothing'
org.gnome.settings-daemon.plugins.power lid-close-suspend-with-external-monitor false
org.gnome.settings-daemon.plugins.power button-hibernate 'nothing'
org.gnome.settings-daemon.plugins.power idle-dim true
org.gnome.settings-daemon.plugins.power button-power 'nothing'
org.gnome.settings-daemon.plugins.power lid-close-battery-action 'suspend'
org.gnome.settings-daemon.plugins.power priority 0
org.gnome.settings-daemon.plugins.power idle-brightness 30
org.gnome.settings-daemon.plugins.power active true
org.gnome.settings-daemon.plugins.power critical-battery-action 'suspend'
org.gnome.settings-daemon.plugins.power button-suspend 'nothing'
org.gnome.settings-daemon.plugins.power button-sleep 'nothing'
org.gnome.settings-daemon.plugins.power percentage-critical 3
org.gnome.settings-daemon.plugins.power sleep-inactive-ac-timeout 3600
org.gnome.settings-daemon.plugins.power sleep-inactive-ac-type 'nothing'
org.gnome.settings-daemon.plugins.power ambient-enabled true
org.gnome.settings-daemon.plugins.power notify-perhaps-recall true
org.gnome.settings-daemon.plugins.power percentage-low 10
org.gnome.settings-daemon.plugins.power percentage-action 2
org.gnome.settings-daemon.plugins.power sleep-inactive-battery-type 'suspend'
org.gnome.settings-daemon.plugins.power time-low 1200
org.gnome.settings-daemon.plugins.power sleep-inactive-battery-timeout 1200
org.gnome.settings-daemon.plugins.power time-action 120
org.gnome.settings-daemon.plugins.power use-time-for-policy true

cat /etc/systemd/logind.conf

[Login]
#NAutoVTs=6
#ReserveVT=6
#KillUserProcesses=no
#KillOnlyUsers=
#KillExcludeUsers=root
#InhibitDelayMaxSec=5
HandlePowerKey=ignore
HandleSuspendKey=ignore
HandleHibernateKey=ignore
#HandleLidSwitch=suspend
#HandleLidSwitchDocked=ignore
#PowerKeyIgnoreInhibited=no
#SuspendKeyIgnoreInhibited=no
#HibernateKeyIgnoreInhibited=no
#LidSwitchIgnoreInhibited=yes
#HoldoffTimeoutSec=30s
#IdleAction=ignore
#IdleActionSec=30min
#RuntimeDirectorySize=10%
#RemoveIPC=yes
#InhibitorsMax=8192
#SessionsMax=8192
#UserTasksMax=33%

Have you any ideas what could be wrong?
Thank you for your help.


Get this bounty!!!

#StackBounty: #linux #fedora #hibernate #btrfs #luks btrfs, LUKS, swapfile: How to hibernate on swapfile?

Bounty: 50

I’m using btrfs encrypted by LUKS on fedora 32 silverblue, kernel version 5.7.7 with anaconda installer default setting.

Because fedora installer automatic partition does not add swap partition or file (or I’ve done wrong), I added swapfile on myself for hibernation like this:

$ # swapfile under /var directory because the location is the only part user can modify on fedora silverblue
$ touch /var/swapfile
$ chattr +C /var/swapfile 
$ fallocate --length 10GiB /var/swapfile
$ sudo chown root /var/swapfile 
$ sudo chmod 600 /var/swapfile 
$ sudo mkswap /var/swapfile 
$ sudo swapon /var/swapfile

and I added swapfile_t attr for selinux:

$ ls -Z /var/swapfile
unconfined_u:object_r:swapfile_t:s0 /var/swapfile

Then I followed arch wiki instruction(https://wiki.archlinux.org/index.php/Power_management/Suspend_and_hibernate#Hibernation_into_swap_file_on_Btrfs).

my /var/swapfile‘s physical offset is 19793240064 and page size is 4096, so I added kernel param with grub. here’s part of my /etc/default/grub kernel params now:

GRUB_CMDLINE_LINUX="rd.luks.uuid=luks-572bfd87-6fa7-4be1-8c73-4759ac9af3cd rhgb quiet resume=UUID=572bfd87-6fa7-4be1-8c73-4759ac9af3cd resume_offset=4832334"

here’s my blkid:

$ sudo blkid
/dev/nvme0n1p1: UUID="5490-E733" BLOCK_SIZE="512" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="46ecd0d1-6722-4b92-af73-9574a58eb332"
/dev/nvme0n1p2: UUID="c9294f4d-9c92-4c08-a037-715223443f2b" BLOCK_SIZE="4096" TYPE="ext4" PARTUUID="731852d5-26cd-43bb-8904-c4256247f97d"
/dev/nvme0n1p3: UUID="572bfd87-6fa7-4be1-8c73-4759ac9af3cd" TYPE="crypto_LUKS" PARTUUID="e74de89a-fe5f-402f-a3bf-e398ad069b5b"
/dev/sda: BLOCK_SIZE="512" UUID="C602B4D602B4CD25" TYPE="ntfs"
/dev/mapper/luks-572bfd87-6fa7-4be1-8c73-4759ac9af3cd: LABEL="fedora_fedora" UUID="337b2fcb-a61b-4976-89ac-2b3feee02963" UUID_SUB="932cfe1c-9713-4063-bda0-a8a792654c39" BLOCK_SIZE="4096" TYPE="btrfs"

and hibernation failed. it seems resume parameter problem. I tried UUID=572bfd87-6fa7-4be1-8c73-4759ac9af3cd and UUID=337b2fcb-a61b-4976-89ac-2b3feee02963 and both failed. What were wrong? How can I setup swapfile hibernate properly?

I’ve checked journalctl -u systemd-logind and found the message but that didn’t help:

...
 localhost.localdomain systemd-logind[936]: Failed to open swap file /var/swapfile to determine on-disk offset: Permission denied
...


Get this bounty!!!

#StackBounty: #encryption #swap #hibernate Failure when recovering from hibernation with encrypted drive on Ubuntu 20.04. Swapfile prio…

Bounty: 50

I used to hibernate on my laptop whose disk is encrypted, under ubuntu 20.04, following the instruction given here and here (except that I didn’t manage to make it work before ubuntu 20.04 because of nvidia drivers issues…).

But for some times, it does not work anymore: at recovering, after I type my encryption password, it hangs forever…

I first problem that I have is that I don’t really know how to "debug" this issue…

Then I wonder if the problem could come from swap priority. When I compare to here, my priorities are in wrong order.

root@is241395:~# swapon 
NAME      TYPE      SIZE USED PRIO
/swapfile file       40G   0B   -3
/dev/dm-2 partition 980M   0B   -2

Can my problem comes from this. How to update these priorities (I am not sure to understand the relation with the fstab)?

Thanks!


Get this bounty!!!

#StackBounty: #windows-10 #sleep #hibernate #sd-card #windows-10-v1709 Why does the attached SD card often not show up after sleep?

Bounty: 50

I have a low end Windows 10 PC that I use to read PDFs and such stuffs. It has Intel Celeron processor with 4GB DDR3 RAM. I have inserted a Micro SD card (128GB) where I keep all the stuffs installed.

Since some days, I am facing this strange problem. When I put my PC to sleep and come back later to wake it up, I can’t access anything that is stored on this memory card (D:). If I try opening an app that is installed in this drive, it just won’t open. This happens very, very often, if not always.

When I navigate to This PC, I find that the card is simply not detected. Restarting the PC, however, solves this issue.

I searched about this problem in this forum and came across this: Internal SD Card Drive not Returning/Waking up after Sleep/Hibernate

The above question was raised for an Apple product, and there is no accepted answer for it yet. Can anyone help me in this regard?

EDIT: So, after days of experimentation, I saw that the problem doesn’t occur if I put my PC to sleep without opening any applications. But, as soon as I open an application, for example: the Opera Browser or the Adobe reader, and put it to sleep, then after waking up, the problem still persists.

I have tried hibernating as well, and it was strange that it behaved exactly the same way as is done after waking up from sleep mode. However, sleep and hibernation are two quite different in nature – sleep stores everything in RAM, while hibernation keeps everything in hard disk.
But I am confused why they’re behaving similarly.

Can anyone shed light on this issue now, after having this much of details?


Get this bounty!!!

#StackBounty: #java #performance #hibernate #join #hibernate-criteria How to get batching using the old hibernate criteria?

Bounty: 200

I’m still using the old org.hibernate.Criteria and get more and more confused about fetch modes. In various queries, I need all of the following variants, so I can’t control it via annotations. I’m just switching everything to @ManyToOne(fetch=FetchType.LAZY), as otherwise, there’s no change to change anything in the query.

What I could find so far either concerns HQL or JPA2 or offers just two choices, but I need it for the old criteria and for (at least) the following three cases:

  • Do a JOIN, and fetch from both tables. This is OK unless the data is too redundant (e.g., the master data is big or repeated many times in the result). In SQL, I’d write
    SELECT * FROM item JOIN order on item.order_id = order.id
    WHERE ...;
  • Do a JOIN, fetch from the first table, and the separation from the other. This is usually the more efficient variant of the previous query. In SQL, I’d write
    SELECT item.* FROM item JOIN order on item.order_id = order.id
    WHERE ...;

    SELECT order.* FROM order WHERE ...;
  • Do a JOIN, but do not fetch the joined table. This is useful e.g., for sorting based on data the other table. In SQL, I’d write
    SELECT item.* FROM item JOIN order on item.order_id = order.id
    WHERE ...
    ORDER BY order.name, item.name;

It looks like without explicitly specifying fetch=FetchType.LAZY, everything gets fetched eagerly as in the first case, which is sometimes too bad. I guess, using Criteria#setFetchMode, I can get the third case. I haven’t tried it out yet, as I’m still missing the second case. I know that it’s somehow possible, as there’s the @BatchSize annotation.

  • Am I right with the above?
  • Is there a way how to get the second case with the old criteria?

Update

It looks like using createAlias() leads to fetching everything eagerly. There are some overloads allowing to specify the JoinType, but I’d need to specify the fetch type. Now, I’m confused even more.


Get this bounty!!!

#StackBounty: #java #spring #postgresql #hibernate #stream-processing efficiently store a result stream in multiple tables with optimis…

Bounty: 100

Given a result stream with a lot of items I want to store them and handle potential concurrency conflicts:

public void onTriggerEvent(/* params */) {
  Stream<Result> results = customThreadPool.submit(/*...complex parallel computation on multiple servers...*/).get();
  List<Result> conflicts = store(results);
  resolveConflictsInNewTransaction(conflicts);
}

I am stuck on how to approach implementing store(...) efficiently. The Result consists of two immutable and detached objects describing data that needs to be updated in their respective DB tables.

@Value
public static class Result {
    A a; // describes update for row in table a
    B b; // describes update for row in table b
}

A and B each reference two users, where (u1, u2) is a key on the respective DB table.

@Value
public static class A {
    long u1;
    long u2;
   // ... computed data fields ...
}
// B accordingly

The stream-calculation itself might be triggered concurrently (multiple onTriggerEvent invocations in parallel) which is mostly fine, but sometimes might result in conflicts for some results (about 0,1% is in conflict, e.g. a stream has a result for (53,21) and another invocation also updated (53,21) in the meantime). The conflict of A and/or B is indicated by their updatedAt fields that would be different in comparison to the beginning of the operation. Here, of course, we do not want to throw away all results and just try again, but only want to resolve the rows in conflict.

So I wonder what is a good approach to (1) store all Result.a and Result.b that are not in conflict and (2) get a List of Results that are in conflict and need special treatment.

public List<Result> store(Stream<Result> results) {
  // store all a
  // store all b (ideally without using results * 2 RAM)
  // do update other stuff if a and b are not in conflict and do it in the same ACID transaction as the update of the related a and b.
  // return those in Conflict
}

How can I implement it without unpacking each result, sending it to the db in its own transaction etc? Ideally, I need send all at once to the DB and get a list of conflicts that have not been stored (and the other should have been persisted). I am open to a different approach as well.

We use JPA/Hibernate if that is relevant.


Get this bounty!!!

#StackBounty: #hibernate #spring-boot #spring-data-jpa #hibernate-envers Hibernate Envers doesn't save referenced column value in c…

Bounty: 50

Here’s the code for 2 entities, machine and device.

@Audited
@Entity(name = "device")
@Table(name = "device")
public class Device {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "machineCode", referencedColumnName = "machineCode")
    private Machine machine;

}

@Audited
@Entity(name = "machine")
@Table(name = "machine")
public class Machine {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String machineCode;

}

Now, when i save the device entity. The machineCode column (in the auditing table of device) gets the value of id and not the corresponding machineCode from machine’s domain object.
I am not sure if there is anything wrong with the code or not. Thanks in advance.

PS – there are other intermingled entities attached to machine entity as well. So, adding @OneToMany is not required or i should say, it would be an overhead.


Get this bounty!!!

#StackBounty: #java #hibernate #jdbc JDBC Query vs JPA Query Performance

Bounty: 50

I am having some issues related with performance while reading thousands of records from the database. I noticed that a pure JDBC query is much more faster that a JPA Native query.

Here is the query

select ID, COL_A, COL_B, COL_C, COL_D, COL_E, COL_F from MY_SUPER_VIEW_V v 
where 1=1 
and v.ID in (:idList)
and v.DATE_FROM <= :date
and v.DATE_TILL >= :date;

This query returns around 38.000 records.

The in idList has more than 1000 records and because I am using an Oracle DB it needs to be split in n queries.

Further i have a method that coverts the Object[] result to my List<Entity>.

In order to understand the performance issue i created a pure JDBC query and a JPA Native query respectively to compare the results.

Here are the timings.

################ getScoresPureJDBCWithListIds ################
List of Ids retrieved. It took: 00:00:00.096 to execute query on DB using JDBC
It took: 00:00:01.180 to execute query on DB using JDBC query
Creating 24206 Scores records from DB result It took: 00:00:04.440
It took: 00:00:01.038 to execute query on DB using JDBC query
Creating 14445 Scores records from DB result It took: 00:00:04.307
################ getScoresJPANativeQueryWithListIds ################
It took: 00:06:09.450 to execute query on DB using JPA Native query
Creating 24206 Scores records from DB result It took: 00:00:00.009
It took: 00:04:04.879 to execute query on DB using JPA Native query
Creating 14445 Scores records from DB result It took: 00:00:00.007

With Hibernate analytics

################ USING FETCH_SIZE: 2000 ################
################ getSmartESGScoresPureJDBCWithListCsfLcIds ################
List of Securities CsfLcId retrieved. It took: 00:00:00.296 to execute query on DB using JDBC
It took: 00:00:11.940 to execute query on DB using JDBC query
Creating 24206 Smart Esg Scores records from DB result It took: 00:00:02.670
It took: 00:00:13.570 to execute query on DB using JDBC query
Creating 14445 Smart Esg Scores records from DB result It took: 00:00:02.553
################ getSmartESGScoresJDBCTemplateWithListCsfLcIds ################
List of Securities CsfLcId retrieved. It took: 00:00:00.087 to execute query on DB using JDBC
Creating 24206 Smart Esg Scores records from DB result It took: 00:00:04.063
Creating 14445 Smart Esg Scores records from DB result It took: 00:00:04.064
################ getSmartESGScoresJPANativeQueryAsESGenius with hint fetch size 2000 ################
2020-04-22 09:36:30.830  INFO 13262 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
    1232369 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    1448702 nanoseconds spent preparing 1 JDBC statements;
    3992364 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}
List of Securities CsfLcId retrieved. It took: 00:00:00.261 to execute query on DB using JDBC
2020-04-22 09:47:23.739  INFO 13262 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
    73670 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    805772 nanoseconds spent preparing 1 JDBC statements;
    651947762290 nanoseconds spent executing 1 JDBC statements; ==> 10 minutes
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}
It took: 00:10:52.898 to execute query on DB using JPA Native query
Creating 24206 Smart Esg Scores records from DB result It took: 00:00:00.018
2020-04-22 09:56:00.792  INFO 13262 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
    2758010 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    3096653 nanoseconds spent preparing 1 JDBC statements;
    516148003151 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}
It took: 00:08:37.032 to execute query on DB using JPA Native query
Creating 14445 Smart Esg Scores records from DB result It took: 00:00:00.006

For the JDBC query I can see 1) that executing the query is quite fast, but 2) processing each ResultSet element in a loop takes the most of the time 00:09 seconds int total

On the other for the JPA Native query 1) executing the query by calling the query.getResultList() method takes a lot of time 10:14 seconds on the other hand 2) processing each result is quite fast here. Analytics shows that a huge amount of time is spent on executing 1 JDBC statement. Even with FETCH_SIZE = 2000 nothing changed significantly.

Why JPA Native is quite slow when compare with pure JDBC? Would it be the type conversions? In my case I am talking about varchar2 and numbers. I was expecting identical results to JDBC. but from 8 seconds to 10mins its a lot.

What can I do to improve the JPA Native query?


Get this bounty!!!

#StackBounty: #java #hibernate #spring-data-jpa #aop #spring-aop AOP To Detect All Class Casts For Hibernate.unproxy()

Bounty: 100

I want to be able to write an aspect to detect when I am casting something in one of my org.mypackage classes.

package org.mypackage;

class Foo {
  public static void main(String[] args) {
    Bar casted = (Bar) args[0]; // want to detect this casting action!
  }
}

How do you write a pointcut to express the casting operation, not just for Foo class, but for any class in org.mypackage?

Background: So Hibernate 5 + Spring Data JPA requires casting entities with inheritance:

if (isInstanceOfMyEntity(someEntity)) {
  // formerly, this was sufficient:
  // MyEntity myEntity = (MyEntity) someEntity;
  // now, this is required *everywhere* it is casted:
  MyEntity myEntity = (MyEntity) Hibernate.unproxy(someEntity);
  ...
}

…which, on a large code base, is scary to consider because there are a lot of places this could break. So if it’s possible to write an aspect/pointcut to at least detect it, then we can at least log it and also identify places in our tests where the issue needs addressing.

This technique is recommended in this question How to convert a Hibernate proxy to a real entity object by @Vlad-Mihalcea.


Get this bounty!!!

#StackBounty: #java #hibernate #java-stream #projection #querydsl Java using filtering at different models before and after the project…

Bounty: 500

Consider the following JAVA model for hibernate:

@Entity
@Table
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long id;

    @Column
    public String firstName;

    @Column
    public String lastName;

    @Column
    public Boolean active;
}

and the following model for API serialization (using spring boot rest controller):

public class PersonVO {
    public Long id;
    public String fullName;
}

What i want is to:

  • Have some filtering applied at the Person (statically defined)
  • Have some filtering applied at the PersonVO (get from @RequestParam)

In C# .NET i could make like:

IQueryable<Person> personsQuery = entityFrameworkDbContext.Persons;
// FIRST POINT - Here i could make some predefined filtering like 'only active', 'from the same city'... at the database model
personsQueryWithPreDefinedFilters = personsQuery.Where(person => person.active == true);


IQueryable<PersonVO> personsProjectedToVO = personsQueryWithPreDefinedFilters.Select(person => new PersonVO()
{
    id = person.id,
    fullName = person.firstName + " " + person.lastName
});
// SECOND POINT - At this point i could add more filtering based at PersonVO model
if (!String.IsNullOrWhiteSpace(fullNameRequestParameter)) {
    personsProjectedToVO = personsProjectedToVO.Where(personVO => personVO.FullName == fullNameRequestParameter);
}

// The generated SQL at database is with both where (before and after projection)
List<PersonVO> personsToReturn = personsProjectedToVO.ToList();

What i got in Java is:

CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
CriteriaQuery<PersonVO> cq = cb.createQuery(PersonVO.class);
Root<Person> root = cq.from(Person.class);
// FIRST POINT - Here i could make some predefined filtering like 'only active', 'from the same city'... at the database model
cq.where(cb.equal(root.get(Person_.active), true));         

Expression<String> fullName = cb.concat(root.get(Person_.firstName), root.get(Person_.lastName));
cq.select(cb.construct(
        PersonVO.class,
        root.get(Person_.id),
        fullName
        ));
// SECOND POINT - At this point i could add more filtering based at PersonVO model??? HOW???
if (fullNameRequestParameter != null) {
    cq.where(cb.equal(fullName, fullNameRequestParameter));
// i only could use based at the fullName expression used, but could i make a Predicate based only on PersonVO model without knowing or having the expression?
}

I want to have separated the “projection to the VO model” from the “where expression” applied to it, but have it indirectly applied if used a projected column (like fullName).

Is this possible in Java? Using what? Criteria? Querydsl? Stream? (don’t get necessarily stick to the java sample)


Get this bounty!!!