output
stringlengths 9
26.3k
| input
stringlengths 26
29.8k
| instruction
stringlengths 14
159
|
---|---|---|
It's always possible that server will terminate unexpectedly, no
matter what type of socket or IPC mechanism is used. It can happen for
many different reasons, for example:it may crash because of software bug, for because due to
segmentation fault or failed assertionit may eat too much memory and can get killed by Linux OOM killer
(it's very easily reproducible in virtual machine)it may be killed erroneously by another user. Linux is multi-user
system and it's possible that someone could accidentally killed your
process, say they wanted to type kill 1112 but typed kill 1111
insteadShould developers consider possible interruption in their codes?Yes, they always should. Read manpage of the function you're going to
use and read all possible values of errnos that the function can set
and always prepare for the worst.
|
When using TCP & UDP sockets, there are many scenarios which cause connection interruption (slow connection, network reset, etc).
Is there any possible situation which an unix domain socket automatically disconnects or interrupts because of an external reason?
Should developers consider possible interruption in their codes?
| Possible scenarios for Unix domain sockets interruption |
No, that's not possible with the standard openssh-portable.
You can look for instance at the unix_listener() function here.
Maybe there are patches floating around, but I'm not going to answer with google search results ;-)
Adding such a thing should be technically easy, but who's going to deal with the "political" part, ie. convince the openssh developers to include the patch?
FWIW, such a patch should necessarily check the peer credentials of the clients connecting to the socket by default; openssh already includes the necessary compat code for that.
|
I've discovered that OpenSSH is capable of forwarding UNIX sockets like this:
ssh -R /var/run/program.sock:/var/run/program.sockMy question is whether this extends to abstract unix sockets too.
I've tried the following to no avail:
ssh -nNT -R @laminar:@laminar
ssh -nNT -R unix-abstract:laminar:unix-abstract:laminarThe program in question does support file-based unix sockets, but as it uses abstract sockets by default I'd like to avoid reconfiguring it to simplify matters if possible.OpenSSH (client) version: OpenSSH_7.4p1 Raspbian-10+deb9u4, OpenSSL 1.0.2q 20 Nov 2018
OpenSSH (server) version: OpenSSH_7.6p1 Ubuntu-4ubuntu0.1, OpenSSL 1.0.2n 7 Dec 2017 | Forward abstract unix socket over SSH? |
I was facing the same issue. You have to disable SELinux. For detailed steps please follow the link:
http://blog.odoobiz.com/2017/11/rhel-wsgi-nginx-error-permission-denied.html
|
I've set permissions on the socket to 777 yet Nginx keeps stating that it's being denied permission to access, and yes I've restarted the server.
Nginx is being started as root (not the best way but it's just the way it is and I'm not the one who set it this way) and the socket in question is owned by a user for the app.
If it's important, the socket is for a rails app running on a puma web-server.
The distro I'm using is Redhat.
I've tried following what I found here but when I try to run
grep nginx /var/log/audit/audit.log | audit2allow -m nginxI get this error:
compilation failed:
mynginx.te:6:ERROR 'syntax error' at token '' on line 6:/usr/bin/checkmodule: error(s) encountered while parsing configuration
/usr/bin/checkmodule: loading policy configuration from mynginx.teThinking it might be the command I'm running I tried:
sudo cat /var/log/audit/audit.log | grep nginx | grep denied | audit2allow -M mynginxbut I still get the same error, after opening the audit log in less and doing a search for anything related to nginx or even denied, I get nothing, there is nothing in the audit.log related to nginx.
I'm trying to do the same thing for another system with a different app (same OS) and again I'm running into the same issue however according other audit log (which finally shows something I get this:
type=USER_CMD msg=audit(1508924031.284:1165419): user pid=30802 uid=502 auid=502 ses=5121 msg='cwd="/home/user/selinux-nginx-rhel/nginx" cmd=73656D6F64756C65202D69206E67696E782E7070 terminal=pts/0 res=success'if it's showing res=success why is nginx still being denied?
Also, when I try audit2allow for this project I get a blank policy.te file like this in this user question of course the underlining cases is probably not the same as I'm running on RHEL.
Also, I'm not sure if SElinux is running but doing getenforce returns: Disabled.
I think ultimately it's a user permissions issue as moving the socket location to place any one can access solves the issue.
| nginx errors with failed (13: permission denied) for socket despite socket permissions being set to 777 |
Consider this Python3 example.
Server A:
#!/usr/bin/env python3
# coding=utf8from subprocess import check_call
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler# Restrict to a particular path
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/JRK75WAS5GMOHA9WV8GA48CJ3SG7CHXL',)# Create server
server = SimpleXMLRPCServer(
('127.0.0.1', 8888),
requestHandler=RequestHandler)# Register your function
server.register_function(check_call, 'call')# Run the server's main loop
server.serve_forever()Server B:
#!/usr/bin/env python3
# coding=utf8import xmlrpc.clienthost = '127.0.0.1'
port = 8888
path = 'JRK75WAS5GMOHA9WV8GA48CJ3SG7CHXL'# Create client
s = xmlrpc.client.ServerProxy('http://{}:{}/{}'.format(host, port, path))# Call your function on the remote server
s.call(['alarm']) |
I want one of machine have a remote control alarm running that can be triggered by any remote machine. More preciselyMachine A is running the service in the background
Any remote machine B can send a packet to machine A to trigger the alarm (a command called alarm)How would you suggest do do it?
I would use nc:Service on machine A:
nc -l 1111; alarmMachine B triggers the alarm with
nc <IP of machine A> 1111I can also write some python to open a socket...
| Remote control alarm |
Of course, you can use any protocol.
Try tcptraceroute.
Or the standard traceroute.
from man page: -I, --icmp
Use ICMP ECHO for probes -T, --tcp
Use TCP SYN for probes -U, --udp
Use UDP to particular destination port for tracerouting (instead
of increasing the port per each probe). Default port is 53
(dns). -UL Use UDPLITE for tracerouting (default port is 53). -D, --dccp
Use DCCP Requests for probes. -P protocol, --protocol=protocol
Use raw packet of specified protocol for tracerouting. Default
protocol is 253 (rfc3692). |
I often run into a situation where I want to traceroute an IP without root or NET_RAW cap in Linux.
I have attempted to send a UDP packet with a small TTL but no ttl error is emitted at all. It seems that getting the TTL exceeded error requires using an ICMP socket. Is it possible to use UDP or TCP protocol only without involving ICMP while still getting notified for TTL error so that I can traceroute with limited capabilities?
| It is possible to traceroute without touching ICMP? |
You guess wrong.
The only property which is per-file descriptor and which can be changed with fcntl(F_SETFD) is the FD_CLOEXEC close-on-exec flag.
All the other properties are either per file object ("open file description" in POSIX lingo -- which can be changed with fcntl(F_SETFL)), or per inode.
Setting the non-blocking flag with fcntl(F_SETFL, | O_NONBLOCK) or with ioctl(FIONBIO) will affect all the file descriptors that refer to that open file. There is also no way to make a file non-blocking only for reading or writing.
This is far from ideal -- you can also refer to this Q&A on StackOverflow, especially the link to the lkml discussion about a failed attempt to fix it somehow.
Notice that regular files are basically non-blocking -- a poll(2) or select(2) on them will return immediately.
If you're only interested in sockets, you should use send(2) or recv(2) with the MSG_DONTWAIT flag instead of read(2) or write(2). Contrary to what you say, a socket file descriptor can be shared between processes, and no matter what its family/protocol/options are. And that also applies to a listening socket.
|
I am more interested in sockets than regular files, but basically I want to know whether one process can "see" a socket as blocking where another process can see it as non-blocking. I am guessing yes, and that the kernel handles all of this depending on what options were used in the syscall.
I guess this would be more about Unix domain sockets than TCP sockets since I don't think 2 different processes could use the same TCP socket (but I could be wrong)
| Can one processes have a descriptor that is non-blocking while another process have a descriptor referencing the same file/socket that is blocking? |
screen processes don’t maintain socket connections while they’re running; they open and close socket connections as needed when they have messages to send. Thus, when you run screen -r to reconnect to an existing session, it connects to the existing process using a socket, negotiates various settings, and when it’s good to go, attaches to the appropriate terminal, and closes the socket.
That means that when you run netstat, unless you happen to do so exactly when two screen processes are communicating (which doesn’t happen all that often), you won’t see an open socket connecting two screen processes.
|
From https://unix.stackexchange.com/a/485290/674Further down in the netstat output is UNIX sockets:
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags Type State I-Node PID/Program name Path
<snip>
unix 2 [ ACC ] STREAM LISTENING 21936 1/systemd /run/dbus/system_bus_socket
<snip>
unix 3 [ ] STREAM CONNECTED 28918 648/dbus-daemon /run/dbus/system_bus_socketWe can see that both of these processes are using the UNIX socket at
/run/dbus/system_bus_socket. So if you knew one of the processes,
looking at this, you should be able to determine the other end.Does that mean any pair of server and client processes based on Unix domain socket should appear in the output of netstat like the one above? In other words, should netstat always show both server and client processes?
GNU Screen also runs as server and client processes based on Unix domain socket, so should they appear in the output of netstat? Why does netstat in fact not show Screen client but only Screen server process like the one below,
$ sudo netstat -ap | grep -i screen
unix 2 [ ACC ] STREAM LISTENING 4533106 27525/SCREEN /run/screen/S-t/27525.testwhile ps shows both?
$ ps aux | grep -i screen
t 19686 0.0 0.0 45096 3292 pts/7 S+ 22:19 0:00 screen -r test
t 27525 0.0 0.0 45780 3292 ? Ss 07:22 0:00 SCREEN -S testThanks.
| Why doesn't `netstat` show Screen client but only Screen server process? |
channel 41: open failed: connect failed: open failedThis error message means that the remote SSH server was unable to perform a TCP forward request, because it couldn't connect to the target of the tunnel. The last "open failed" part of the message is an error message from the remote SSH server.
When you run SSH with a port forward, the port forward works like this:The local ssh client listens for TCP connections on the local port (/var/run/some.socket in your case).
When an originator connects to the local port, the ssh client sends a request for a "direct-tcpip" channel to the server. The request includes the target of the tunnel (/var/run/some.socket on the remote system in your case).
The remote SSH server makes a TCP connection to the target of the tunnel.
The local ssh client and the remote ssh server relay data in both directions between the respective TCP connections and the direct-tcpip channel.In your case, the ssh server is failing at step 3 because it can't connect to the target of the tunnel for some reason.
You should check the ssh log on the remote server. The SSH server process may have logged a message saying why it's failing. Aside from that, you say this is happening intermittently during a load test, so I'd look at server-side issues related to load. A couple of possibilities come to mind:The application on the remote system which is listening on /var/run/some.socket isn't handling connection requests quickly enough, and a backlog is building up.
The SSH server process is hitting some kind of resource limit (number of open file descriptors, for example) |
I'm running ssh running on macOS to redirect connections to local Unix domain socket to a domain socket on another machine. The command line for ssh call is roughly the following:
$ ssh -nNT -L /var/run/some.socket:/var/run/some.socket -o TCPKeepAlive=yes \
-o ServerAliveCountMax=10 -o ServerAliveInterval=60 user@destinationAfter performing some load testing, I discovered that on occasion some client connections fail, and upon examining logs, I found the following error output from ssh at the same time that the connections fail:
channel 41: open failed: connect failed: open failed
channel 44: open failed: connect failed: open failed
channel 47: open failed: connect failed: open failed
channel 49: open failed: connect failed: open failed
channel 51: open failed: connect failed: open failed
channel 59: open failed: connect failed: open failed
channel 62: open failed: connect failed: open failed
channel 64: open failed: connect failed: open failedThe load test parameters are to run 100 concurrent connections (connect, send some data, receive some data, disconnect with total of 10,000 connections to be performed.)
The behavior observed is that at the beginning of the test when first set of connections are created very quickly, few connections fail with the above errors. How many fails ranges from run to run but usually between couple to a dozen or so. Most failures tend to happen at the beginning of the test, though at times occur later in the test (i.e. after first 100 had been made).
Other posts on SO with similar descriptions seem to be covering the issue of using localhost with workaround to use 127.0.0.1, which here makes it not relevant since it is not a TCP/IP socket. Also, the destination part in the above command is specified as an IP address already.
A bit at a loss on how to fix and trace the issue. I tried using -vvv to get detailed dumped of ssh operation with nothing fruitful (all it logs for the relevant channels is that socket was set to non-blocking).
Note that the call to ssh is done from a script, and the call is preceded with ulimit -n 1024 which should provide more than enough file descriptors to be available to service all the sockets.
| ssh: channel xx: open failed: connect failed: open failed |
You missed this in that same unix(7) manpage you're quoting from:On Linux, connecting to a stream socket object requires write permission on that socket; sending a datagram to a datagram socket likewise
requires write permission on that socket.Of course, you also need search(execute) permission to all the leading directories from its path, just like with any other file.
The part you're quoting refers to creating a socket, which only happens when bind(2)ing to it, which is what nc -l -U /path/to/sock does. Again, just like with creating any other file, the umask will affect the permissions of the created socket (umask == 022 => no write permission for other users => they cannot connect to the socket):
$ umask
0022
$ nc -Ul sock
^C
$ ls -l sock
srwxr-xr-x 1 xxx xxx 0 Oct 16 18:35 sock
^ ^ ^Binding to a unix domain socket always has to create it from scratch. You cannot bind to an existing file, that will fail with EADDRINUSE. Consequently, most programs (including nc) will forcefully remove any file with the same name before binding to it:
$ echo text > file
$ strace nc -l -U file
...
socket(AF_UNIX, SOCK_STREAM, 0) = 3
unlink("file") = 0
bind(3, {sa_family=AF_UNIX, sun_path="file"}, 110) = 0
listen(3, 5) = 0
accept4(3, NB: both snippets talk about the on-disk "socket" special file / inode, not about the inode representing the active socket object (which appears in /proc/<pid>/fd, /proc/net/unix, etc):
$ nc -lU sock &
[1] 4424
$ ls -li sock
20983212 srwxr-xr-x 1 xxx xxx 0 Oct 17 18:01 sock
^^^^^^^^
$ ls -li /proc/4424/fd
total 0
43825 lrwx------ 1 xxx xxx 64 Oct 17 18:02 0 -> /dev/pts/4
43826 lrwx------ 1 xxx xxx 64 Oct 17 18:02 1 -> /dev/pts/4
43827 lrwx------ 1 xxx xxx 64 Oct 17 18:02 2 -> /dev/pts/4
43828 lrwx------ 1 xxx xxx 64 Oct 17 18:02 3 -> socket:[46378]
^^^^^
$ grep 46378 /proc/net/unix
00000000ee8c0faa: 00000002 00000000 00010000 0001 01 46378 sock |
I'm trying to understand the permissions of a unix domain socket, when using an existing file, umask changes are required as well as the dir permissions.
If I create a world readable dir as root and open a socket with netcat:
root$: mkdir /tmp/mydir
root$: chmod 777 /tmp/mydir
root$: nc -l -U /tmp/mydir/sockThen as a non root user try to connect to aforementioned socket it fails, though the dir is world readable as per:
https://man7.org/linux/man-pages/man7/unix.7.htmlIn the Linux implementation, pathname sockets honor the
permissions of the directory they are in. Creation of a new
socket fails if the process does not have write and search
(execute) permission on the directory in which the socket is
created.root$: runuser -u user1 -- nc -U /tmp/mydir/sock
nc: unix connect failed: Permission deniedNow by doing umask 0, and restarting the same socket again, it can be connected to from the non root user.
root$: umask 0
root$: nc -l -U /tmp/mydir/sockroot$: runuser -u user1 -- nc -U /tmp/mydir/sock
ping Furthermore modifying the /tmp/mydir permissions to chmod 600 will stop the non root user from accessing the socket again.
root$: chmod 600 /tmp/mydir
root$: runuser -u user1 -- nc -U /tmp/mydir/sock
nc: unix connect failed: Permission deniedIt's clear the dir permissions work as intended according to the manual, but why is umask 0 required if the parent dir has the correct permissions ? Is netcat still creating some sort of other file ?
| unix domain socket permissions and umask integration between root and non root users |
No, you can't connect using ssh to UNIX domain socket simulating serial console. You would need SSHD server on the other side and your machines probably pre-dates the whole SSH protocol.
You got this probably confused by the forwarding of UNIX domain socket, which is possible as port-forwarding.
|
I have some old unix running as vm on VirtualBox server
those vm had the serial ports simulated by unix socket
for example: an old AT&T 2.1 SVr4 has socket on /tmp/att1
to connect i did
minicom -D unix#/tmp/att1on server.
I heard somewhere ssh can connect to unix sockets.
How to do?
I have tried
socat TCP-LISTEN:5500 EXEC:'ssh user@server "socat STDIO UNIX-CONNECT:/tmp/att1"'Then
ssh server -p 5500But give me error
ssh_dispatch_run_fatal: Connection to 192.168.0.2: message authentication code incorrectAlso tried
ssh -R/tmp/att1:/tmp/att1 -R127.0.0.1:1233:/tmp/att1But failed with remote port failed error.
Suggestions?
| ssh on unix socket |
You can put your socket in /var/tmp which is a world writable dir with the sticky bit, like /tmp.
If your program is a daemon started by systemd you could consider using RuntimeDirectory=somedir in the unit file, then that dir will be created in /run when your unit starts, and removed when it stops. You could then create your socket in /run/somedir/.
|
I have a C++ program which must communicate with other services (including httpd), and does so via a socket in /tmp
With the advent of systemd and the PrivateTmp=true setting, processes like httpd can no longer see my program's socket by default. I don't want users to change the PrivateTmp setting of httpd since it's a good protection.
However, where should I put my socket file (which creates created/deleted on start/stop of my service) so that it can be shared with other processes?
(Or is the only/right solution to tell users to turn PrivateTmp off ??)
| Where to put socket so PrivateTmp can be true |
No. You can't communicate across hosts on a network using AF_UNIX sockets, as those reference local inodes on the filesystem to bind the socket to, and the local filesystem is only available to the local host.
To communicate between nodes, you'll need to use an AF_INET socket, which will bind to an IP address and port, which could be reachable to a different host.
|
Actually, I have software that runs in the ARM-Linux has three apps of mine.I want to run the one certain application in Linux host x86.
The internal components in my ARM-Linux program communicate using Unix domain socket.
My socket type is: AF_UNIX
I am using old ARM processor doesn't support Valgrind. There is some memory leak in the application that is causing the crash. So I build the application in the host and figuring out how to establish communication between ARM and x86 using domain socket?Now I have a situation where the application foo is in ARM and bar is Linux x86. Question is it possible to communicate between the different host?I thought Unix domain sockets are inter-domain after reading the below link, I got confused.
I read,UNIX domain sockets are a method by which processes on the same
host can communicate. Communication is bidirectional with stream
sockets.
fd = socket(AF_UNIX, SOCK_STREAM, 0); | Using Unix domain socket for different hosts |
Found the answer. The part I needed was "IDENTIFIED VIA unix_socket" as shown below:
MariaDB [(none)]> CREATE USER serg IDENTIFIED VIA unix_socket;
MariaDB [(none)]> GRANT ALL PRIVILEGES on mydatabase.* to 'serg'@'localhost';MariaDB [(none)]> select user, host, password, plugin from mysql.user;
+--------------+-----------+----------+-------------+
| user | host | password | plugin |
+--------------+-----------+----------+-------------+
| root | localhost | | unix_socket |
| root | mitra | | unix_socket |
| root | 127.0.0.1 | | unix_socket |
| root | ::1 | | unix_socket |
| serg | localhost | | unix_socket |
+--------------+-----------+----------+-------------+
5 rows in set (0.00 sec)MariaDB [(none)]> FLUSH PRIVILEGES;Then in the shell:
sudo service mysql restartTo log in using user 'serg' do not use sudo. Just use mysql -u serg.
|
I just installed MariaDB on Kubuntu 15.10. I am able to log in with the root user via the plugin that authenticates the user from the operating system. (This is new to me, so I am learning about it rather than removing the plugin authentication as most tutorials seem to recommend.)
Now I want to create a non-root user and grant all privileges to that user and allow the user to log into mysql (on localhost) without a password (using just the plugin). How would I do this? Do I need to give the user a password too?
| MariaDB: Create and grant a new user using unix sockets plugin (passwordless) |
In general Unix Domain Sockets cannot communicate between host OS and guest OS.
Unix Domain Sockets are, like e.g. Named Pipes, bound to the OS kernel. If you open the same Unix Domain Socket file node in the host and the guest, you get two different virtual network connections. One in the host kernel and one in the guest kernel. These are completely separate and cannot intercommunicate.
This doesn't apply iff host OS and guest OS share the same kernel, e.g. when using Linux namespaces/containers instead of real virtualization. Then it's possible to use Unix Domain Sockets to communicate between the systems.
For communication between two different OS kernels you need to use a real network protocol like IPv4/IPv6 or measures specific to the used virtualization software.
|
Is it a true statement that, shared memory does not work between a host OS and guest OS, but a Unix Domain Socket (specifically udp) can communicate between the two?
An in depth explanation would be appreciated, thanks!
| Unix Domain Socket with VM |
The ~ must be expanded by some program. Usually this program is the shell. The sshd daemon doesn't feed the path to a shell and doesn't expand the path.
But you don't need an expansion for the current users home directory as it is the working directory anyway.
Try
ssh -vvv -N -R ~/.gnupg/S.gpg-agent:${HOME}/.gnupg/S.gpg-agent.extra {HOST}Edit:
This works because the working directory on the host (not on the client) is always the home directory of the target user.
The ssh server doesn't expand ~ of environment variables, but it should be possible to execute code on the host to create a link or symlink to a known location that can be used by the ssh server.
Edited as suggested by Kusalananda
|
I am trying to forward a gpg-agent Unix socket to a remote machine. I have tried the following two versions of the remote forwarding command:A: ssh -vvv -N -R ~/.gnupg/S.gpg-agent:~/.gnupg/S.gpg-agent.extra {HOST}
B: ssh -vvv -N -R ~/.gnupg/S.gpg-agent:/home/{USER}/.gnupg/S.gpg-agent.extra {HOST}They both report successful remote forwarding after initial ssh connection. However, option A's socket fails with debug1: connect_next: host ~/.gnupg/S.gpg-agent.extra ([unix]:~/.gnupg/S.gpg-agent.extra): No such file or directory when an actual data connection is attempted on the remote machine with gpg-connect-agent /bye while option B's socket works fine.
I want to know whether it is possible to do local home directory expansion with ssh remote forwarding command. If not, why?
| Does OpenSSH >=7.2 support local-side tilde expansion for remote Unix socket forwarding |
I'm no python programmer, but I guess you should special case your code based on sys.platform.
SO_PEERCRED is not a standardized interface, and the actual structure / binary interface is different between the systems.
On Linux, as defined in /usr/include/bits/socket.h:
struct ucred {
__u32 pid;
__u32 uid;
__u32 gid;
};On OpenBSD, as defined in /usr/include/sys/socket.h:
struct sockpeercred {
uid_t uid; /* effective user id */
gid_t gid; /* effective group id */
pid_t pid;
};(uid_t, gid_t and pid_t are also 32bit on OpenBSD)
Other systems (eg. solaris, FreeBSD) have a completely different interface -- for some code that gets the peer credentials in a "system-independent" manner you could look at the update_client_creds() function from the heimdal source code (which is using the getpeereid(3) library function on OpenBSD and FreeBSD instead of directly SO_PEERCRED or LOCAL_PEERCRED).
In any case, the credentials got this way will be those of the process that called connect(2) or listen(2) on the socket (a process that may no longer exist), not necessarily those of the process actually using the socket by writing to or reading from it.
|
I'm trying to get the Unix socket peer credentials in python.
I am using this piece of code for that:
peercred = conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
pid, uid, gid = struct.unpack("3i", peercred)This works correctly in Linux, but in OpenBSD the order is different.
In OpenBsd the order is [uid, gid, pid] instead.
What is causing this difference? How do I know when to use which order?
The linux systems I tried were running on a x86_64 architecture and the openbsd system was on a amd64 architecture.
| Different order for getsockopt SO_PEERCRED in Linux and OpenBSD |
systemd has PrivateTmp=true for memcached.service
One way would be to override PrivateTmp, specifically for the memcached.service, i.e.
mkdir -p /etc/systemd/system/memcached.service.d
echo "[Service]" > /etc/systemd/system/memcached.service.d/override.conf
echo "PrivateTmp=false" >> /etc/systemd/system/memcached.service.d/override.conf
systemctl daemon-reload
systemctl restart memcachedThat would change the memcached.service back to using /tmp, rather than /tmp/systemd-private-...
Assuming you want to use memcached for session handling; Once you've verified that /tmp/memcahced.sock exists with the correct permissions, in /etc/php.ini or /etc/php/conf.d/memcached.ini change session support.
[Session]
extension=memcached.so
session.save_handler="memcached"
session.save_path="/tmp/memcached.sock"If it exists, comment out session.save_handler=files.
|
I'm in the process of upgrading from Ubuntu Server 16.04 to 18.04 and at the same time upgrading from PHP 5.6 to PHP 7.
In /etc/memcached.conf I added:
-s /tmp/memcached.sock
-a 666When I restart the service, I see:
srw-rw-rw- 1 memcache memcache 0 Nov 13 03:44 /tmp/systemd-private-7fc3b73707084a93bcc6abd22001eb7e-memcached.service-oIF206/tmp/memcached.sock=How can I configure systemd to know where the unix socket is?
| How to configure systemd so that PHP can use memcached unix socket? |
Usually, your ISP gives you a single IP address, and your home router does network address translation (NAT) to pretend to your ISP that all the devices in your home network are just a single device with the same address as the router itself.
Because of this, if anyone wants to contact your home network from the outside, the router has to "forward a port" to the device in your home network where the service is running, because the only IP address visible from the outside is the router's IP address.
If you don't want that, the only alternative is either to run your service directly on the router, or disconnect the router from your ISP and instead connect the computer where the services run directly (if it has the hardware to do so).
There is no other way, no matter what protocol you use.
You can also pay your ISP to give your more than one IPv4 address (this will be expensive). Or, if your ISP gives you an IPv6 global prefix, then each of the devices in your home network will have its own IPv6 address, which is reachable from the outside. So there's no NAT, no port forwarding is necessary, but it will only work for IPv6.
OTOH, setting up port forwarding isn't exactly black magic, so just do it.
Edit
When you "visit a web site", i.e. your local http client will contact the remote http server, the NAT in the router will rewrite the source address of the outgoing packets from the address of your private device to the ISP's IP address. It will also remember that a local device opened an outgoing connection, and when incoming packets arrive that belong to that connection, it will conversely rewrite the destination address and send them to the local device. That's what NAT is.
So for outgoing connections from your local device, you don't need port forwarding. NAT handles this for you. For incoming connections, e.g. if you run a http server, you need to tell your router "please forward port 80 to the following local device".How can i open the port without accesing router settings?For incoming connections, you can't. As I already tried to explain.
Edit
If you google example programs for UDP, there'll always be a server listening on a port, and a client not listening, but contacting the server (and after that both server and client can exchange packets in any direction). So "how do you receive info without listening to a port" is that you write the client, not the server, and then the server can send data to the client, so the client "receives info".
You can't run the server behind NAT without port forwarding. Period. No matter how often you ask. Not for TCP, not for UDP, not by "using a low level protocol".
If you don't want to enable port forwarding in the GUI of the router: Many routers allow you to set port forwarding, sometimes even temporary port forwarding, via UPnP. Your router may or may not have this feature.
There are also other tricks, like first contacting a general kind of server, which then will establish a connection with some other peer behind NAT (see e.g. the STUN protocol).
But if you are behind NAT, you first have to contact a server on the "real" internet. This server will be listening on a port, your client won't. Or, if you have a server listening to a port, you need to set up port forwarding. There is no other choice. Live with it.
|
I am doing UDP socket programming in C. In order to listen to a port, I need to forward ports in my router. My question is how to avoid doing that and still being able to communicate over the internet, if not possible with sockets, what is the lowest level possible? In other words, every device can listen to an http server, so is http the only unlocked way to go?
| How to avoid forwarding ports? |
knxd github repository at https://github.com/knxd/knxd mentions where the socket is created:
"If you use Debian Jessie or another systemd-based distribution, /lib/systemd/system/knxd.socket is used to open the "standard" sockets on which knxd listens to clients. You no longer need your old -i or -u options."
It also advises using /run/ instead of /tmp:
"knxd's Unix socket should never have been located in /tmp; the default is now /run/knx. You can add a -u /tmp/eib (or whatever) option if necessary, but it's better to fix the clients."
|
I run an Ubuntu based server on raspi (6.5.0-1015-raspi #18-Ubuntu). On this system, I have knxd running, exposing a KNX bus to my server, and then Home Asssitant in a docker container. knxd and docker are configured as systemctl services.
knxd is configured to create a UNIX domain socket in /tmp/eib, with the command line argument -u /tmp/eib. This works when I start the service, e.g. using systemctl start, once the system is running.
However after reboot, there's a directory in /tmp/eib, owned by root:root, which blocks knxd from creating its domain socket. knxd then (understandably) crashes on start. When I manually remove the directory with sudo rm -rf /tmp/eib, and then systemctl restart knxd, knxd manages to create the correct socket and start up successfully.
# after reboot. With this in place, knxd crashes on startup.
$ ll -d /tmp/eib
drwxr-xr-x 2 root root 4096 Apr 27 09:33 /tmp/eib/
# If I manually remove the file...
$ sudo rm -rf /tmp/eib
$ sudo systemctl restart knxd
# ... wait a bit ...
# ... then knxd comes up successfully and creates the correct file+permissions
$ ll -d /tmp/eib
srwxr-xr-x 1 knxd knxd 0 Apr 27 09:39 /tmp/eib=
# now knxd and everything depending on it works fineHow do I debug who's creating this file? How do I set things up such that knxd comes up successfully after a reboot?
| Unix socket in /tmp turns into directory on reboot |
You have to switch to the correct network namespace first, because socket state is per namespace (namely per network namespace). For example by using nsenter. sudo has to be moved first, because nsenter also requires privileges. In one line (and using ss's own filtering features) this becomes:
sudo nsenter -t $(docker inspect --format='{{.State.Pid}}' python-app) --net -- \
ss -a -np sport == 9001 |
I run a python code inside docker container performing the following calls
import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);
s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",9001));s1.listen(1);c,a=s1.accept();I'm trying to get info using ss and see the open sockets, but can't get themdocker run --rm --publish 9001:9001 -it --name python-app sample-python-app reverseshell.pydocker inspect --format='{{.State.Pid}}' python-app
1160502> sudo ss -a -np | grep 9001
tcp LISTEN 0 4096 0.0.0.0:9001 0.0.0.0:* users:(("docker-proxy",pid=1160459,fd=4))
tcp LISTEN 0 4096 [::]:9001 [::]:* users:(("docker-proxy",pid=1160467,fd=4)) however lsof gives me more info:
> sudo lsof -p 1160502
lsof: WARNING: can't stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
Output information may be incomplete.
lsof: WARNING: can't stat() fuse.portal file system /run/user/1000/doc
Output information may be incomplete.
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python 1160502 dmitry cwd DIR 0,1364 108 19497 /workspace
python 1160502 dmitry rtd DIR 0,1364 188 256 /
python 1160502 dmitry txt REG 0,1364 6120 6529 /layers/paketo-buildpacks_cpython/cpython/bin/python3.10
python 1160502 dmitry mem REG 0,30 6529 /layers/paketo-buildpacks_cpython/cpython/bin/python3.10 (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 9492 /layers/paketo-buildpacks_cpython/cpython/lib/python3.10/lib-dynload/_posixsubprocess.cpython-310-x86_64-linux-gnu.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 9518 /layers/paketo-buildpacks_cpython/cpython/lib/python3.10/lib-dynload/fcntl.cpython-310-x86_64-linux-gnu.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 9514 /layers/paketo-buildpacks_cpython/cpython/lib/python3.10/lib-dynload/array.cpython-310-x86_64-linux-gnu.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 9527 /layers/paketo-buildpacks_cpython/cpython/lib/python3.10/lib-dynload/select.cpython-310-x86_64-linux-gnu.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 9520 /layers/paketo-buildpacks_cpython/cpython/lib/python3.10/lib-dynload/math.cpython-310-x86_64-linux-gnu.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 9499 /layers/paketo-buildpacks_cpython/cpython/lib/python3.10/lib-dynload/_socket.cpython-310-x86_64-linux-gnu.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 634 /lib/x86_64-linux-gnu/libm-2.27.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 692 /lib/x86_64-linux-gnu/libutil-2.27.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 619 /lib/x86_64-linux-gnu/libdl-2.27.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 670 /lib/x86_64-linux-gnu/libpthread-2.27.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 609 /lib/x86_64-linux-gnu/libc-2.27.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 6705 /layers/paketo-buildpacks_cpython/cpython/lib/libpython3.10.so.1.0 (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 591 /lib/x86_64-linux-gnu/ld-2.27.so (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 3735 /usr/lib/locale/locale-archive (path dev=0,32, inode=1544914)
python 1160502 dmitry mem REG 0,30 1365 /usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache (stat: No such file or directory)
python 1160502 dmitry mem REG 0,30 1091 /usr/lib/locale/C.UTF-8/LC_CTYPE (stat: No such file or directory)
python 1160502 dmitry 0u CHR 136,0 0t0 3 /dev/pts/0
python 1160502 dmitry 1u CHR 136,0 0t0 3 /dev/pts/0
python 1160502 dmitry 2u CHR 136,0 0t0 3 /dev/pts/0
python 1160502 dmitry 3u sock 0,8 0t0 75159952 protocol: TCPat least I have this line showing that fd=3 opens socket [75159952] but without actual port number.
python 1160502 dmitry 3u sock 0,8 0t0 75159952 protocol: TCPso how to find with ss information about open socket over port 9001 that is not docker-proxy?
| ss doesn't display socket info related to the process opening SOL_SOCKET |
You have set up a listening datagram socket with socat+UNIX-RECV: and are attempting to talk to it via a stream socket with nc.
The second scenario works because in that case you added the missing -u flag to nc, so that both it and socat were employing a datagram socket. It wasn't anything to do with there being a proxy.
Further readinghttps://unix.stackexchange.com/a/294221/5132 |
I'm trying to debug why data isn't being sent over a Unix Domain Socket.
I have 2 applications which should be communicating over a UDS but aren't.
To test I've done the following:
Using socat, I listen on a socket like this:
socat -x -u UNIX-RECV:/tmp/dd.sock STDOUT
and using netcat to send data like this:
echo "hello" | nc -U -w1 /tmp/dd.sock
nothing happens.
But if I also set up socat as a proxy, to listen to a UDP port, and write that to the socket like this:
socat -s -u UDP-RECV:9988 UNIX-SENDTO:/tmp/dd.sock
Then sending via netcat to the UDP port works:
echo "Hello" | nc -u localhost 9988
I've also been able to get my client application to write UDP to the proxy and it's successful where is wasn't when writing to the unix socket.
I would like to understand why socat doesn't receive data written to it by nc, but does if I proxy over UDP.
Using Amazon Linux
4.14.101-75.76.amzn1.x86_64
| Sending data to Unix socket failing unless proxied with socat via UDP |
The server code calls accept() only once. Thus, only the first connection attempt is effectively accepted and the remaining client connections are kept on a connection request queue which lives in the kernel space. The next client connection will be retrieved from the queue when accept() is called again.
No process owns client connections while they remain in kernel space, because multiple processes or threads may legally accept connections from an unique pair of address and port if they enable SO_REUSEPORT option on all participating socket descriptors.
You can test the SO_REUSEPORT option by yourself by adding the following code snippet before the bind() call and running more than one server. You will figure that the kernel will distribute requests among them.
{
int enabled = -1;
if (setsockopt (sockd, SOL_SOCKET, SO_REUSEPORT,
(void*) &enabled, sizeof (enabled)) < 0) {
perror ("setsockopt");
}
}Reference from man 2 accept:The accept(sockfd) system call is used with connection-based socket types (SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections for the listening socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket. The newly created socket is not in the listening state. The original socket sockfd is unaffected by this call.Reference from man 7 socket:SO_REUSEPORT (since Linux 3.9)
Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.
For TCP sockets, this option allows accept(2) load distribution in a multi-threaded server to be improved by using a distinct listener socket for each thread. This provides improved load distribution as compared to traditional techniques such using a single accept(2)ing thread that distributes connections, or having multiple threads that compete to accept(2) from the same socket.
For UDP sockets, the use of this option can provide better distribution of incoming datagrams to multiple processes (or threads) as compared to the traditional technique of having multiple processes compete to receive datagrams on the same socket. |
i am testing stuff with sockets and i encountered that strange case :
i coded i very simple tcp server in c, i made it block after accept(), just to see what happen when accepting multiple connection attempts at the same time :
Here is an excerpt of code of the server :
//listen()
if( (listen(sock,5)) == -1) {
perror("listen");
exit(-1);
}//accept()
if( (cli = accept(sock, (struct sockaddr *) &client, &len)) == 1 ){
perror("accept");
exit(-1);
}printf("entrez un int : ");
scanf("%d",&toto);when the server asks the user to enter an integer, i try to connect multiple clients with telnet.
Fort the first one, evrything is ok :
root@[...] :/home/[...]/workspace/sockets# netstat -antp | grep 10003
tcp 0 0 0.0.0.0:10003 0.0.0.0:* LISTEN 25832/toto
tcp 0 0 127.0.0.1:10003 127.0.0.1:51166 ESTABLISHED 25832/toto
tcp 0 0 127.0.0.1:51166 127.0.0.1:10003 ESTABLISHED 25845/telnetbut then after the first one, even though i am root, there are some connections i can't see the process owning it and its pid :
root@[...] :/home/[...]/workspace/sockets# netstat -antp | grep 10003
tcp 0 0 0.0.0.0:10003 0.0.0.0:* LISTEN 25832/toto
tcp 0 0 127.0.0.1:10003 127.0.0.1:51166 ESTABLISHED 25832/toto
tcp 0 0 127.0.0.1:51166 127.0.0.1:10003 ESTABLISHED 25845/telnet
tcp 0 0 127.0.0.1:10003 127.0.0.1:51168 ESTABLISHED -
tcp 0 0 127.0.0.1:51168 127.0.0.1:10003 ESTABLISHED 25852/telneta third one :
root@[...] :/home/[...]/workspace/sockets# netstat -antp | grep 10003
tcp 0 0 0.0.0.0:10003 0.0.0.0:* LISTEN 25832/toto
tcp 0 0 127.0.0.1:10003 127.0.0.1:51166 ESTABLISHED 25832/toto
tcp 0 0 127.0.0.1:51166 127.0.0.1:10003 ESTABLISHED 25845/telnet
tcp 0 0 127.0.0.1:10003 127.0.0.1:51172 ESTABLISHED -
tcp 0 0 127.0.0.1:10003 127.0.0.1:51168 ESTABLISHED -
tcp 0 0 127.0.0.1:51168 127.0.0.1:10003 ESTABLISHED 25852/telnet
tcp 0 0 127.0.0.1:51172 127.0.0.1:10003 ESTABLISHED 25860/telnetI tried again a few days later with netstat -antpe as root and here is what i got :
root@[...] :/home/[...]/workspace/sockets# netstat -antpe | grep 10003
tcp 0 0 0.0.0.0:10003 0.0.0.0:* LISTEN 1000 327680 22399/toto
tcp 0 0 127.0.0.1:33286 127.0.0.1:10003 ESTABLISHED 1000 417202 22884/telnet
tcp 0 0 127.0.0.1:10003 127.0.0.1:33046 ESTABLISHED 0 0 -
tcp 0 0 127.0.0.1:10003 127.0.0.1:33286 ESTABLISHED 0 0 -
tcp 0 0 127.0.0.1:33044 127.0.0.1:10003 ESTABLISHED 1000 332810 22402/telnet
tcp 0 0 127.0.0.1:33046 127.0.0.1:10003 ESTABLISHED 1000 331200 22410/telnet
tcp 0 0 127.0.0.1:10003 127.0.0.1:33044 ESTABLISHED 1000 332801 22399/totohow comes a process or a connection can have an inode of 0 ? Can someone explain me what is going on ?
| sudo netstat -antp not showing PID |
If portability is desired, then at least 2 pipes must be created. This corresponds to 2 open file description compared to 1 as is the case with a socket.
Although not a performance/efficiency reason, you cannot use MSG_PEEK with pipes, but you can use it with anonymous sockets, like those created with socketpair(2).
|
Suppose I want to launch a co-process and attach its standard input and output to the main process, what we have here are 2 options:call pipe(2) and create 2 pipes, and attach them separately to the standard input and output of the co-process.call socketpair(2) and attach 1 end of the socket to the standard input and output of the co-process.It's well-known that a simple pipe can be implemented more efficiently than a "socket pair", and that's what many systems are doing nowadays. But what if we need it to work in both directions? Is a "pipe pair" still more efficient than a socket-pair?
Context
I want to write standard-conforming codes to the best of my effort, therefore the target platform is assumed to be "POSIX-in-general". What I intend to mean with this is that, this question asks for a comparison of the general implementation techniques for the 2 types of IPC as deployed on major implementations, including Linux, {Free,Net,Open}BSD(s), some SVR4 descendants such as Solaris 11.4, etc.
Also, by expensive, I mean more than just IO throughput - system resource consumption is also among my concerns.
| Is 2 pipes more expensive than 1 socketpair? |
I have a solution, but it's in python which is not ideal for dependency reasons.
# simple.socket
[Unit]
Description=Socket[Socket]
ListenStream=11111
Accept=no# simple.service
[Unit]
Description=Meta-service
Wants=simple-child.service[Service]
ExecStart=/usr/local/bin/listen.py# simple-child.service
[Unit]
Description=Child1
PartOf=simple.service[Service]
ExecStart=sleep infinityAnd the python script is:
#!/usr/bin/env python3from socketserver import TCPServer, StreamRequestHandler
import socketclass Handler(StreamRequestHandler):
def handle(self):
while True:
c = self.rfile.read(1)
if len(c) == 0:
exit()class Server(TCPServer): SYSTEMD_FIRST_SOCKET_FD = 3 def __init__(self, server_address, handler_cls):
TCPServer.__init__(self, server_address, handler_cls, bind_and_activate=False)
self.socket = socket.fromfd(self.SYSTEMD_FIRST_SOCKET_FD, self.address_family, self.socket_type)if __name__ == "__main__":
HOST, PORT = "12.34.56.78", 12345 # This gets overridden by systemd
server = Server((HOST, PORT), Handler)
server.serve_forever()Now when the connection is established, simple.service and simple-child.service both launch. When the connection is killed simple.service stops, but somehow simple-child.service doesn't stop despite the PartOf= relationship. Adding ExecStop=systemctl stop simple-child.service to simple.service does work, but that's not a great solution.
|
I'm trying to launch a meta-service remotely through a socket. Requirements: The socket should start the meta-service when a connection is established
The meta-service should start all child (Wants=) services upon start
When the connection is closed, the meta-service should stop
When the meta-service stops, it should stop all child (ConsistsOf=) servicesI'm not expecting multiple connections, so my requirements are undefined if multiple connections are made.
Here's one attempt:
# simple.socket
[Unit]
Description=Socket[Socket]
ListenStream=11111
Accept=no# simple.service
[Unit]
Description=Meta-service
Wants=simple-child.service # Will be a full tree of dependencies[Service]
ExecStart=-cat - # cat will fail to start because it doesn't accept connections
StandardInput=socket# simple-child.service
[Unit]
Description=Child1
PartOf=simple.service # Puts a ConsistsOf= relationship in simple.service[Service]
ExecStart=sleep infinity # Business goes hereThe problem here is that when Accept=no, the ExecStart= is responsible for handling the incoming connections. cat - doesn't call accept() and so simple.service will fail to start. Is there another basic tool I could use in ExecStart= which would accept() the connections, but close when the a connection is stopped? It could be the first or last connection, I'm agnostic to that. That would be the easiest solution which also solves the rest of the question. Is there an example of a C-application which uses accept() so I could figure out how systemd passes sockfd for our first argument accept(int sockfd, ...)? Then I could write something myself. I tried running this, but I kept getting failures when using bind().
Here's another attempt using Accept=yes:
# simple.socket
[Unit]
Description=Socket[Socket]
ListenStream=11111
Accept=yes# [emailprotected] # Note the template here
[Unit]
Description=Meta-service
Wants=simple-child.service[Service]
ExecStart=-cat - # now cat will work!
StandardInput=socket# simple-child.service
[Unit]
Description=Child1
[emailprotected] # This fails to connect to the instance[Service]
ExecStart=sleep infinity # Business goes hereIn this case, everything starts great. When the connection is closed, [emailprotected] stops nicely, but simple-child.service keeps running. That's because [emailprotected] does not refer to the correct instance. I'd REALLY prefer to avoid templating simple-child.service, but let's try it:
# simple.socket
[Unit]
Description=Socket[Socket]
ListenStream=11111
Accept=yes# [emailprotected]
[Unit]
Description=Meta-service
Wants=simple-child@%i.service % Starts simple-child as a template[Service]
ExecStart=-cat -
StandardInput=socket# [emailprotected] # Newly templated
[Unit]
Description=Child1
PartOf=simple@%i.service # Using %i [Service]
ExecStart=sleep infinity # Business goes hereIn this case [emailprotected] is templated as [emailprotected]:11111-127.0.0.1:49276.service, but %i is only 6. It spawns [emailprotected] which is only [emailprotected] and so it fails to stop when [emailprotected]:11111-127.0.0.1:49276.service stops.
| Stop child services when systemd socket connection closes |
The s at the start of the line in ls -l's output identifies that as a unix-domain socket. The = at the end is a type indicator for sockets, one that ls -F adds. So the file itself is called just 0.
Unix sockets are a particular method of interprocess communication that mostly acts like real network sockets but have names in the filesystem, which allows the usual filesystem access controls to apply to the sockets. That "file" you have there is one such name.
The socket pseudo-files tend to linger around (uselessly) after the process that opened them has exited, unless something takes care to remove them. But they can be removed like any file. (Well, on Linux, at least.) E.g. with nc creating a unix socket and rm removing it:
$ nc -U -l socket &
[1] 22480
$ ls -l
total 0
srwxr-x--- 1 ilkkachu ilkkachu 0 Aug 10 00:45 socket=
$ rm socket
$ ls -l
total 0
$ kill %1If rm doesn't give an error, it should mean it was able to remove the file. Of course, that wouldn't stop the file from being recreated afterwards.
|
How can I remove below file?
srwxrwxrwx 1 patroh root 0 Aug 8 16:11 0=The user patroh is myself. The rm command won't work - it doesn't give any error when I execute rm 0.
I am not sure how I created this file?
| how to remove file 0= file which has srw permission |
One of your linked answers directly quotes the apache documentation for mod_proxy_fcgi. According to the answer it states:UDS does not currently support connection reuseBut this phrase no-longer exists in the documentation.
It was there when the answer was written on 26 jan 2017. The first snapshot on waybackmachine where it was removed is 10 Aug 2017.
I haven't managed to find reference to this being "fixed" in the commit history. The statement was removed from the documentation in SVN commit 1802336 AKA git commit 2a3f6ec2 simply with the comment:UDS does support reuse
jimjagConclusion
mod_proxy_fcgi does support connection reuse for unix domain sockets. ...Not withstanding any unreported bugs.
|
Do unix domain sockets support reuse?
Lots of conflicting information about this online. I suspect a lot of it is just outdated, but I'm no expert.
Do I ProxySet enablereuse=on if my handler is a socket? e.g.
<Proxy "fcgi://matching-worker-string/" max=10>
# Unsure about this:
ProxySet enablereuse=on
</Proxy><FilesMatch "\.php$">
<If "-f %{REQUEST_FILENAME}">
SetHandler proxy:unix:/run/php/php.sock|fcgi://matching-worker-string/
</If>
</FilesMatch>Many comments online state that they're not supported, and state you can even check the Apache docs for proof, but I don't see it. Maybe they didn't have reuse support in 2015-2017, but do now?
Edit
Apache 2.4, php-fpm 7.3, mod_proxy_fcgi
| Do unix domain sockets support reuse? |
If the receiver is not reading as fast as the sender sends, then the sockets buffers fill up after a while.
When assuming a datagram socket type a blocking socket would block if the buffers are full and thus implicitly slow down the sender. With a non-blocking socket the sending of a message simply would fail and EAGAIN would be returned as error by send. Note that this is true only for unix domain sockets of type datagram. With UDP sockets the send will succeed and messages would simply be lost.
With a stream socket a partial message might be written, no matter if the socket is blocking or non-blocking. The sender needs to check how many bytes are actually written (return of send) and make sure to send the remaining data later. With a non-blocking socket the send also could fail completely with EAGAIN, with a blocking socket it would instead block and wait for the receiver reading some data in order to have space again in the socket buffer.
|
I have two processes P1 (sender) and P2 (receiver). P1 uses unix-domain-socket (UDS) to send data to P2. what will happen if P1 sends data at the rate of 100 messages/second and P2 is capable to receive 50 messages/second. Both are non-blocking sockets.
What is happening in the above scenario? will p1 or p2 face memory exhaust after some time?
team, kindly explain what will happen under the hood in the above scenario.
thanks.
| what will happen if receiver unable to handle data velocity through socket? |
uptime
If you want it in numerical form, it's the first number in /proc/uptime (in seconds), so the time of the last reboot is
date -d "$(</proc/uptime awk '{print $1}') seconds ago"The uptime includes the time spent in a low-power state (standby, suspension or hibernation).
|
Is there a command I can type in a terminal that will tell me the last time a machine was rebooted?
| How long has my Linux system been running? |
On my system it gets the uptime from /proc/uptime:
$ strace -eopen uptime
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/libproc-3.2.8.so", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
open("/proc/version", O_RDONLY) = 3
open("/sys/devices/system/cpu/online", O_RDONLY|O_CLOEXEC) = 3
open("/etc/localtime", O_RDONLY|O_CLOEXEC) = 3
open("/proc/uptime", O_RDONLY) = 3
open("/var/run/utmp", O_RDONLY|O_CLOEXEC) = 4
open("/proc/loadavg", O_RDONLY) = 4
10:52:38 up 3 days, 23:38, 4 users, load average: 0.00, 0.02, 0.05From the proc manpage: /proc/uptime
This file contains two numbers: the uptime of the system
(seconds), and the amount of time spent in idle process
(seconds).The proc filesystem contains a set of pseudo files. Those are not real files, they just look like files, but they contain values that are provided directly by the kernel. Every time you read a file, such as /proc/uptime, its contents are regenerated on the fly. The proc filesystem is an interface to the kernel.In the linux kernel source code of the file fs/proc/uptime.c at line 49, you see a function call:
proc_create("uptime", 0, NULL, &uptime_proc_fops);This creates a proc filesystem entry called uptime (the procfs is usually mounted under /proc), and associates a function to it, which defines valid file operations on that pseudo file and the functions associated to them. In case of uptime it's just read() and open() operations. However, if you trace the functions back you will end up here, where the uptime is calculated.Internally, there is a timer-interupt which updates periodically the systems uptime (besides other values). The interval, in which the timer-interupt ticks, is defined by the preprocessor-macro HZ, whose exact value is defined in the kernel config file and applied at compilation time.
The idle time and the number of CPU cycles, combined with the frequency HZ (cycles per second) can be calculated in a number (of seconds) since the last boot.To address your question: When does “uptime” start counting from?
Since the uptime is a kernel internal value, which ticks up every cycle, it starts counting when the kernel has initialized. That is, when the first cycle has ended. Even before anything is mounted, directly after the bootloader gives control to the kernel image.
|
My computer says:
$ uptime
10:20:35 up 1:46, 3 users, load average: 0,03, 0,10, 0,13And if I check last I see:
reboot system boot 3.19.0-51-generi Tue Apr 12 08:34 - 10:20 (01:45) And then I check:
$ ls -l /var/log/boot.log
-rw-r--r-- 1 root root 4734 Apr 12 08:34 boot.logThen I see in /var/log/syslog the first line of today being:
Apr 12 08:34:39 PC... rsyslogd: [origin software="rsyslogd" swVersion="7.4.4" x-pid="820" x-info="http://www.rsyslog.com"] startSo all seems to converge in 8:34 being the time when my machine has booted.
However, I wonder: what is the exact time uptime uses? Is uptime a process that launches and checks some file or is it something on the hardware?
I'm running Ubuntu 14.04.
| On Linux, when does "uptime" start counting from? |
If you have a separate server to run your check script on, something like this would do a simple Ping test to see if the server is alive:
#!/bin/bash
SERVERIP=192.168.2.3
[emailprotected]ping -c 3 $SERVERIP > /dev/null 2>&1
if [ $? -ne 0 ]
then
# Use your favorite mailer here:
mailx -s "Server $SERVERIP is down" -t "$NOTIFYEMAIL" < /dev/null
fiYou can cron the script to run periodically.
If you don't have mailx, you'll have to replace that line with whatever command line email program you have and probably change the options. If your carrier provides an SMS email address, you can send the email to that address. For example, with AT&T, if you send an email to [email protected], it will send the email to your phone.
Here's a list of email to SMS gateways:
http://en.wikipedia.org/wiki/List_of_SMS_gateways
If your server is a publicly accessible webserver, there are some free services to monitor your website and alert you if it's down, search the web for free website monitoring to find some.
|
Background : I need to receive an alert when my server is down. When the server is down, maybe the Sysload collector will not be able to send any alert. To receive an alert when the server is down, I have an external source (server) to detect it.
Question : Is there any way (i prefer bash script) to detect when my server is down or offline and sends an alert message (Email + SMS)?
| Bash script to detect when my server is down or offline |
Load is not equal to CPU usage. It is basically an indicator how many processes are waiting to be executed.
Some helpful links:https://superuser.com/questions/23498/what-does-load-average-mean-in-unix-linux
http://blog.scoutapp.com/articles/2009/07/31/understanding-load-averages |
I have a 1 core CPU installed on my PC. Sometimes, uptime shows load >1. How is this possible and what does this mean?
EDIT: The values go up to 2.4
| Why/how does "uptime" show CPU load >1? |
First of all, crtime is tricky on Linux. That said, running something like
$ stat -c %z /proc/
2014-10-30 14:00:03.012000000 +0100or
$ stat -c %Z /proc/
1414674003is probably exactly what you need. The /proc file system is defined by the LFS standard and should be there for any Linux system as well as for most (all?) UNIXen.
Alternatively, assuming you don't really need seconds precision, but only need the timestamp to be correct, you can use who:
$ who -b
system boot 2014-10-30 14:00From man who:
-b, --boot
time of last system boot
You can convert that to seconds since the epoch using GNU date:
$ date -d "$(who -b | awk '{print $4,$3}' | tr - / )" +%s
1414674000 |
I'm aware of the uptime command, but it returns seconds since booted, so if I just substract that number from current timestamp, in theory I can get a different result if second changes after I've read the uptime and current timestamp. uptime -s is what I want, but it is not available on centos (how is it calculated btw?). Can I just get ctime of /proc dir? This seems to give me the proper number, but I wonder if every linux system has /proc created on boot.
| How to reliably get timestamp at which the system booted? |
Here's a way without perl:
awk '{printf("%d:%02d:%02d:%02d\n",($1/60/60/24),($1/60/60%24),($1/60%60),($1%60))}' /proc/uptime |
I want to display /proc/uptime in well format as:
DD:HH:MM:SS/proc/uptime give me up time of system in seconds, is there a standard solution that convert seconds to this format?
| Convert linux sysuptime to well format date |
You're seeing the unexpected loadavg because of high iowait. 98.7 in the wa section of top shows this. From your screenshots I see the kworker process is also in uninterruptible sleep (state of D within top) which occurs when a process is waiting for disk I/O to complete.
vmstat gives you visibility into the run queue. Execute vmstat 1 in typical sar fashion for updates every second.The r column shows runnable/running processes which the kernel uses to calculate loadavg and the b column shows processes blocked waiting for disk I/O aka uninterruptible sleep. Processes in b are added to the loadavg calculation, which is how iowait causes mysterious loadavg.
So to answer your question of how to see which procs are causing high loadavg, in your case of iowait, use top/ps to look for procs in a state of D then troubleshoot from there.
|
I have an Ubuntu server running Redis, which suffers from a high load problem.
Forensics
Uptime
# uptime
05:43:53 up 19 min, 1 user, load average: 2.96, 2.07, 1.52sar
# sar -q
05:24:00 AM LINUX RESTART05:25:01 AM runq-sz plist-sz ldavg-1 ldavg-5 ldavg-15 blocked
05:35:04 AM 0 116 3.41 2.27 1.20 4
Average: 0 116 3.41 2.27 1.20 4htop
The CPU is utilization in htop is embarrassingly low:topnetstat
34 open redis-server connections:
$ sudo netstat -natp | grep redis-server | wc -l
34free
$ free -g
total used free shared buffers cached
Mem: 14 6 8 0 0 2
-/+ buffers/cache: 4 10
Swap: 0 0 0How do I know which processes are causing the high load, waiting to enter the Running state? Is the number of connections too high?
| High load average: Which processes are waiting in the queue? |
/var/log/messagesThat is the main log file you should check for messages related to this. Additionally either /var/log/syslog (Ubuntu) or /var/log/secure (CentOS)
To find out when your server was last rebooted just type uptime to see how long it has been up.
|
It seems that my server keeps restarting. I want to know why.
How can I know when the last time server was rebooted and why?
root pts/0 139.193.156.125 Thu Aug 8 21:10 still logged in
reboot system boot 2.6.32-358.11.1. Thu Aug 8 20:38 - 21:11 (00:33)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 20:15 - 21:11 (00:56)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 19:16 - 21:11 (01:55)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 18:56 - 21:11 (02:14)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 18:24 - 21:11 (02:47)
root pts/1 139.193.156.125 Thu Aug 8 18:16 - crash (00:07)
root pts/0 195.254.135.181 Thu Aug 8 18:10 - crash (00:13)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 17:52 - 21:11 (03:19)
root pts/0 195.254.135.181 Thu Aug 8 17:38 - crash (00:13)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 17:08 - 21:11 (04:02)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 16:58 - 21:11 (04:12)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 16:45 - 21:11 (04:26)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 16:35 - 21:11 (04:36)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 16:27 - 21:11 (04:44)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 15:59 - 21:11 (05:12)
reboot system boot 2.6.32-358.11.1. Thu Aug 8 06:15 - 21:11 (14:56)
root pts/1 208.74.121.102 Wed Aug 7 06:03 - 06:04 (00:00)
root pts/1 208.74.121.102 Tue Aug 6 15:34 - 17:40 (02:05)
root pts/0 139.193.156.125 Tue Aug 6 11:28 - 04:40 (1+17:11)In Linux is there ANY WAY to know why the system rebooted? Specifically did high load cause it? If not that then What?
| How to know why server keeps restarting? |
Uptime is part of the 'procps' package, the upstream source is at http://procps.sourceforge.net/ (Not a fedora user, so not sure where to find their .src.rpm).
To answer the question you didn't ask, however; take a look in /proc/uptime
The first number is seconds since boot. You should be able to turn that into something usable fairly easily :)
|
I am learning Python. Till now I've been doing only basic Python coding. A day ago, I checked python implementation of tree command. Suddenly I thought of creating a Python clone for uptime. I don't have any clue about which language it is implemented in and what would be the complexity involved in cloning it.
But I couldn't find its source code. I am using Fedora 14. kernel-devel package is installed. I did whereis uptime but the resulting /usr/bin/uptime file shows weird symbols when opened using vim. Googling for its source code couldn't yield desired results either. Where can I find its source code?
| Where can I find the source code for `uptime`? |
This isn’t something the firmware tracks, as far as I’m aware. Even BMCs don’t measure total uptime.
This won’t help with past uptime from previous boots, but you can start recording uptimes now, by installing a tool such as uptimed and setting it up so that it never discards values (set LOG_MAXIMUM_ENTRIES to 0 in uptimed.conf). That will measure operating system uptime, not total CPU “on” time, but it should be close enough... Once you’ve got uptimed running, you can run uprecords to view the totals, for example
up 1492 days, 02:57:18 | since Sat Sep 7 00:50:06 2013
down 61 days, 08:11:24 | since Sat Sep 7 00:50:06 2013
%up 96.051 | since Sat Sep 7 00:50:06 2013As pointed out by quixotic, you’ll be able to get some idea of historical uptime by looking at your logs. If you’re running systemd, you can view the boots which have been logged using journalctl --list-boots. Log rotation means that this is likely to miss quite a lot of uptime though.
As pointed out by JdeBP, last reboot might give you a longer list of boots with the associated uptime.
|
Is there any way to read total running time of a linux system from BIOS or CPU?
I've searched BIOS informations by dmidecode. But it gives release date which is not proper for my question.
Then I've checked out /proc. But it holds uptime values just from last reboot. Maybe, writing these uptime values for every boot could be an option.
Then I've checked dumpe2fs. It gives total running time of a particular hard drive. It's useless for me because hdd could be changed while my application is running.
Except these above, how can I read or calculate the total runtime of my system ? Where can I read from ?
| Total runtime of machine |
Depending on your flavor of Unix, the /proc filesystem may have an uptime file somewhere with the information you want.
Linux> cat /proc/uptime
5899847.37 23165596.55And the output of the uptime command for the same time:
Linux> uptime
16:46:27 up 68 days, 6:51, 3 users, load average: 0.01, 0.02, 0.05So 5899847.37/86400 = 68.28527 --> 68 days, 6 hours, 51 minutes.
|
How can I convert the uptime output to seconds since epoch to compare with dmesg output? Does uptime have the same resolution as the kernel message time? Is there a way to more directly get the kernel time than from uptime?
➜ ~ echo "hi" > /dev/kmsg
➜ ~ dmesg | tail
[ 859.214564] hi
➜ ~ uptime
10:08 up 2 days, 43 secs, 2 users, load averages: 1.69 1.64 1.54 | How to print kernel time from command line? |
On any POSIX-compliant system, you can use the etime column of ps.
LC_ALL=POSIX ps -o etime= -p $PIDThe output is broken down into days, hours, minutes and seconds with the syntax [[dd-]hh:]mm:ss. You can work it back into a number of seconds with simple arithmetic:
t=$(LC_ALL=POSIX ps -o etime= -p $PID)
d=0 h=0
case $t in *-*) d=$((0 + ${t%%-*})); t=${t#*-};; esac
case $t in *:*:*) h=$((0 + ${t%%:*})); t=${t#*:};; esac
s=$((10#$d*86400 + 10#$h*3600 + 10#${t%%:*}*60 + 10#${t#*:})) |
Under Linux I can get a process's uptime in seconds with:
echo $(($(cut -d "." -f1 /proc/uptime) - $(($(cut -d " " -f22 /proc/$PID/stat)/100))))But how can I get it under different OS? ex.: SunOS, HP-UX, AIX?
| How to get a process uptime under different OS? |
As log-files are usually deleted after some time, the total up-time is difficult to get.
If the hard disk is as old as the PC, the RAW value (last number) of
smartctl -a /dev/sda | grep Power_On_Hourscould give a rough estimate how many hours the PC was used.
|
I need to find PC uptime from the day of installation until now.
Is this logged somewhere? Does any file log this cumulative uptime?
| Finding PC uptime from first day until now |
[I caught some misconceptions here which I think will this post clear off eventually]
There should not be any difference since both refer to /var/run/utmp file, which has its own format to store the records. If at all there is any difference, then your utmp file is busted. uptime shows the amount of time that has passed since the system has been booted or how long the system has been running. It does not tell you the system clock or system boot time . System boot time information is stored /var/run/wtmp file.
[centos@centos temp]$ date; uptime; who -b
Fri Dec 9 20:41:40 IST 2011
20:41:40 up 1:32, 2 users, load average: 0.50, 0.37, 0.29
system boot 2011-12-09 19:11uptime refers as well /proc/uptime, which essentially keeps the counters in kernel.
[centos@centos temp]$ sleep 1; cat /proc/uptime; uptime; sleep 5; cat /proc/uptime ; uptime
5914.79 5271.83
20:47:39 up 1:38, 2 users, load average: 0.29, 0.31, 0.27
5920.07 5276.80
20:47:44 up 1:38, 2 users, load average: 0.56, 0.36, 0.29/var/run/wtmp is referred by last/lastb commands. who & w refers /var/run/utmp file. last reboot will show a log of all reboots since the log file was created.
Additionally, if you are having /proc filesystem, then tool such as procinfo can give you bootup time as well.
Example:
bash$ procinfo | grep Bootup
Bootup: Wed Mar 21 15:15:50 2001 Load average: 0.04 0.21 0.34 3/47 6829 |
I have a Linux system where it is showing to me two different times when the system was last booted.
root@linux:~ # who -b; uptime
system boot 2009-07-09 20:51
11:48am up 1 day 0:54, 1 user, load average: 0.01, 0.03, 0.00I presume that who is showing the content of /var/log/wtmp and uptime I have no idea.
Is there some way to fix this difference? I rebooted the system yesterday so I know the contents that uptime is showing me is correct.
| Uptime and who -b are showing different times when the system was last booted on Linux |
Since you tag your question with Ubuntu, below is enough.
$ uptime -p
up 4 weeks, 1 day, 1 hour, 1 minutesee man uptime for Ubuntu.
-p, --pretty
show uptime in pretty formatOr with your own script:
awk -F'( |,|:)+' '{
printf("%dweeks, %.fdays, %dhours, %dminutes\n",
$5/7, ($5/7-int($5/7))/0.143+.05, $7, $8)
}' <(uptime)Each day~=0.143 week, and we divided the result to 0.143 to get days, then added 0.5 and with printf' s .f control it will round to next integer number (does as Ceil function).
You may need to change $5, $7 and $8 with $6, $8 and $9.
|
Basically I an using conky to ssh into an android tv box and get the uptime and display it on the conky screen.
I have this so far, found on net and hacked by me but it works, please amend if its crap
uptime | awk -F'( |,|:)+' '{print int($6/7),"weeks",$8,"hours,",$9,"minutes."}'and it shows
4 weeks 1 hour 1 minuteHow do I get
4 weeks **1 day** 1 hour 1 minute | getting uptime in Weeks, Days, Hours, Minutes |
As manuals (and even Wikipedia) point out:/proc/uptime
Shows how long the system has been on since it was last restarted.
The first number is the total number of seconds the system has been up. The second number is how much of that time the machine has spent idle, in seconds. On multi core systems (and some linux versions) the second number is the sum of the idle time accumulated by each CPU.The decimal point separates seconds from fractions of a second. To calculate point in time system booted up using this metrics, you would have to subtract the number of of seconds the system has been up (first number) from current time in epoch format rounding up the fraction.
For example, the boot time stamp in Ruby (accurate to 100ms, limited by /proc/uptime):
`date +%s.%3N`.split[0].to_f - `cat /proc/uptime`.split[0].to_f |
I need to write a script that figures out if a reboot has occurred after an RPM has been installed. It is pretty easy to get the epoch time for when the RPM was installed: rpm -q --queryformat "%{INSTALLTIME}\n" glibc | head -1, which produces output that looks like this: 1423807455.
This cross checks with rpm -q --info.
# date -d@`rpm -q --queryformat "%{INSTALLTIME}\n" glibc | head -1`
Fri Feb 13 01:04:15 EST 2015
# sudo rpm -q --info glibc | grep "Install Date" | head -1
Install Date: Fri 13 Feb 2015 01:04:15 AM EST Build Host: x86-022.build.eng.bos.redhat.comBut I am getting stumped on trying to figure out how to get the epoch time from uptime or from cat /proc/uptime. I do not understand the output from cat /proc/uptime which on my system looks like this: 19496864.99 18606757.86. Why is there two values? Which should I use and why do these numbers have a decimal in them?
UPDATE: thanks techraf
here is the script that I will use ...
#!/bin/shnow=`date +'%s'`
rpm_install_date_epoch=`rpm -q --queryformat "%{INSTALLTIME}\n" glibc | head -1`
installed_seconds_ago=`expr $now - $rpm_install_date_epoch`
uptime_epoch=`cat /proc/uptime | cut -f1 -d'.'`if [ $installed_seconds_ago -gt $uptime_epoch ]
then
echo "no need to reboot"
else
echo "need to reboot"
fiI'd appreciate any feedback on the script.
Thanks
| How do I get the time when the system booted up in epoch format? |
uptimed
One such tool that I came across many years ago is called uptimed. The project site is here: http://podgorny.cz/moin/Uptimed.
This is a pretty straightforward install, given uptimed appears to be in most of the major distros' repositories.
Installation
$ sudo yum install uptimedOnce installed the service needs to be configured so that it will start upon reboots. The stats of differing uptimes can be seen using the command uprecords.
Example
uprecords
# Uptime | System Boot up
----------------------------+---------------------------------------------------
1 371 days, 06:08:04 | Linux 2.6.18-194.8.1.el5 Fri Jan 13 08:03:18 2012
2 322 days, 13:20:22 | Linux 2.6.18-194.8.1.el5 Wed Feb 23 21:17:19 2011
3 243 days, 13:42:00 | Linux 2.6.18-164.15.1.el Thu Jun 24 21:48:01 2010
4 120 days, 11:08:54 | Linux 2.6.18-194.8.1.el5 Sun Jun 2 08:43:41 2013
5 80 days, 21:27:49 | Linux 2.6.18-128.1.1.el5 Fri Jan 1 16:35:06 2010
6 73 days, 21:47:32 | Linux 2.6.18-194.8.1.el5 Sat Jan 19 13:23:17 2013
-> 7 49 days, 00:12:15 | Linux 2.6.18-194.8.1.el5 Mon Sep 30 19:20:13 2013
8 39 days, 06:12:06 | Linux 2.6.18-194.8.1.el5 Tue Apr 23 06:05:01 2013
9 29 days, 16:18:57 | Linux 2.6.18-92.1.13.el5 Thu Jan 1 00:31:43 2009
10 29 days, 12:41:08 | Linux 2.6.18-92.1.18.el5 Thu Feb 12 02:46:39 2009
----------------------------+---------------------------------------------------
1up in 24 days, 21:35:18 | at Fri Dec 13 19:07:32 2013
no1 in 322 days, 05:55:50 | at Tue Oct 7 04:28:04 2014collectd
If you're looking for something more graphical then check out collectd. Main project page is here: http://collectd.org/. Again, should be in most major distros' repositories.
ExampleCollectd can do way more than just collect uptimes. It has a sophisticated plugin API which has dozens of plugins for collecting data on a variety of services such as MySQL or other system related information.
Referencesuptimed source tree - in mercurial |
A tool such as this might on the surface appear to serve no real useful purpose, but people that take care of systems like to brag, and uptime is just one of those things that they like to brag about right after how much RAM or CPUs their systems have.
Additionally, how many times have you had a system mysteriously reboot, only to find that it had, later on. A tool such as this would help to identify the frequency of both the reboots and the length of time that the system was staying up, between reboots. 2 potentially useful pieces of information when debugging badly behaving systems.
Is anyone aware of such a tool?
| Is there a tool for tracking uptimes across reboots? |
You can use UDEV to get the particulars about your system's battery.
connected to power
$ upower -i /org/freedesktop/UPower/devices/battery_BAT0
native-path: /sys/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:0a/PNP0C09:00/PNP0C0A:00/power_supply/BAT0
vendor: Panasonic
model: 42T4801
serial: 624
power supply: yes
updated: Sat Oct 18 13:17:16 2014 (2 seconds ago)
has history: yes
has statistics: yes
battery
present: yes
rechargeable: yes
state: fully-charged
energy: 80.5788 Wh
energy-empty: 0 Wh
energy-full: 80.9892 Wh
energy-full-design: 84.24 Wh
energy-rate: 0.00372912 W
voltage: 12.224 V
percentage: 99.4933%
capacity: 96.141%
technology: lithium-ionon battery
$ upower -i /org/freedesktop/UPower/devices/battery_BAT0
native-path: /sys/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:0a/PNP0C09:00/PNP0C0A:00/power_supply/BAT0
vendor: Panasonic
model: 42T4801
serial: 624
power supply: yes
updated: Sat Oct 18 13:37:36 2014 (22 seconds ago)
has history: yes
has statistics: yes
battery
present: yes
rechargeable: yes
state: discharging
energy: 79.9524 Wh
energy-empty: 0 Wh
energy-full: 80.9892 Wh
energy-full-design: 84.24 Wh
energy-rate: 17.172 W
voltage: 11.94 V
time to empty: 4.7 hours
percentage: 98.7198%
capacity: 96.141%
technology: lithium-ion
History (charge):
1413653856 98.720 discharging
1413653826 98.893 discharging
1413653796 99.080 discharging
1413653766 99.293 discharging
History (rate):
1413653856 17.172 discharging
1413653826 17.399 discharging
1413653796 17.453 discharging
1413653766 17.345 dischargingI've never seen anything that shows the time that's elapsed on battery, so you'll have to calculate it from the above output. Also this output will typically show a "time to charge" which is a rough indicator of how long it was on power.
|
How to know system uptime under battery ?
so that i can get exact time of battery backup
the uptime shows complete uptime (AC/Battery)
NOTE : I am using linux Mint 17.
| get system uptime on battery? |
Use uptime command. Yes, it includes sleep time, if you don't want to include it see:How to find the uptime since last wake from standby?. There is no way to distinguish between restart and shutdown, without parsing logs.
|
First and foremost I want to know how long my laptop (unix, apple, OSX 10.9 mavericks) has been 'awake' (i.e. how long its been open, or since it last 'slept'). I' also be interested in how long since the last restart, and time since the last shutdown (if those two things can be differentiated). I've tried the who and w commands, which seem to show me time for the whole system, and for individual processes (terminals?) since the system last restarted.
Is there a way to tell how long the system has been awake, explicitly?
Does the reported process times include sleep-time (i.e. when my laptop is closed)?
Is there a way to distinguish between restart and shutdown?
| How long system has been awake / running / since restart |
You notice the large values of st? Those are "stolen" CPU cycles -- cycles you can't use, because you have completely almost -- or fully -- depleted your CPU credit balance.
The usage is 10% is averaged over some time window, probably 5 minutes. If you watch the output from top, you should see that 100% minus stolen minus idle is approximately 10% over time.
You essentially have no available CPU headroom at this point. A timing-critical workload would be expected to exhibit inconsistent responsiveness under these conditions.
Your workload is too large for a t2.micro. If this were not the case, you'd always have a surplus of CPU credits... essentially, by definition. Unless you can do something to reduce the workload or improve the efficiency of your code, the current symptoms indicate the need for a larger instance class.
|
I am having touble understanding what server resource is causing lag in my Java game server. In the last patch of my game server, I updated my EC2 lamp server from apache2.2, php5.3, mysql5.5 to apache2.4, php7.0, mysql5.6. I also updated my game itself, to include many more instances of monsters that are looped though every game loop - among other things.
Here is output from right when my game server starts up:Here is output from a few minutes later:And here is output from the next morning:As you can see in the images the cpu usage of my Java process levels off around 80% in the last screenshot, yet load avg goes to 1.20. I have even seen it go as high as 2.7 this morning. The cpu credits affect how much actual cpu juice my server has so it makes sense that the percentage goes up as my credits balance diminishes, but why at 80% does my server lag?
On my Amazon EC2 metrics I see cpu at 10% (which confuses me even more):Right when I start up my server my mmorpg does not lag at all. Then as soon as my cpu credits are depleted it starts to lag. This makes me feel like it is cpu based, but when I see 10% and 80% I don't see why. Any help would be greatly appreciated. I am on a T2.micro instance, so it has 1 vCPU. If I go up to the next instance it nearly doubles in price, and stays at same vCPU of 1, but with more credits.
Long story short, I want to understand fully what I going on as the 80% number is throwing me. I don't just want to throw money at the problem.
| CPU and Load Average Conflict on EC2 server |
You would need additional software installed for that. You could use sar (see https://linux.die.net/man/1/sar ) or the monitoring-system of your choice.
sar -q will report load averages (among others...)
$ sar -q 1 5
Linux 4.9.0-9-amd64 (sds-ulm-edv-553-workstation) 09/10/2019 _x86_64_ (2 CPU)02:04:43 PM runq-sz plist-sz ldavg-1 ldavg-5 ldavg-15 blocked
02:04:44 PM 0 158 0.00 0.02 0.10 0
02:04:45 PM 0 158 0.00 0.02 0.10 0
02:04:46 PM 0 158 0.00 0.02 0.10 0
02:04:47 PM 0 158 0.00 0.02 0.10 0
02:04:48 PM 0 158 0.00 0.02 0.10 0
Average: 0 158 0.00 0.02 0.10 0The last line Average: is likely interesting here?
You can give a file to that: sar -q -f /var/log/sa/fileofyourchoice and then further process columns 4-6 of the output.
To get a quick overview of "what happened here?", you will likely need some graphical representation. Unfortunately I have no idea how to pipe sar-outout through GNUplot (or give it to grafana...) or the like to generate something useful.
Okay, this tickled me :-)
Produce a datafile...
LANG=C sar -q 1 250 | grep ':' | awk '{ print $1,$4,$5,$6 }' | sed '1d;$d' > datafile.txtFind the maximal values:
$ datamash -t ' ' max 2 max 3 max 4 < datafile.txt
2.53 1.55 1.1
$ head -1 datafile.txt | cut -d' ' -f1
20:20:53
$ tail -1 datafile.txt | cut -d' ' -f1
20:25:02Now create a file plotting, where you will need those values for xrange and yrange:
$ cat plotting
set title "Load over time"
set xdata time
set style data lines
set term png
set timefmt "%H:%M:%S"
set format x "%H:%M:%S"
set xlabel "Time"
set ylabel "Load"
set autoscale y
set xrange ['20:20:53':'20:25:02']
set yrange ['-0.01':'2.6']
set xtics rotate
set output "load_over_time.png"
plot "datafile.txt" using 1:2 t "loadavg-1" w lines, "datafile.txt" using 1:3 t "loadavg-5" w lines, "datafile.txt" using 1:4 t "loadavg-15" w linesNow you can generate a graphic with $ gnuplot < plotting
`
And now you have a graph in load_over_time.png:If you have a monitoring-system (e.g. check_mk) in place, getting the history you need is much easier.
|
We all know we can get average CPU load as:
uptime
10:09:22 up 2 days, 1:44, 1 user, load average: 20.01, 20.03, 22.05but this shows only
load average over the last 1 minute is 22.05
load average over the last 5 minute is 20.03
load average over the last 15 minute is 20.01We want a list of load averages for the last X hours. Is there any Linux (we're using RHEL) command that can show the history of average CPU load for the last X hours?
| CPU load average + how to get cpu load average for history of X hours |
On Linux, all three commands use different sources of information by default.
uptime uses the information given by the kernel in /proc/uptime. The latter contains two pieces of information: the system’s uptime, including time spent suspended, and the time spent in the idle process. These values are accurate.
who -b uses the information stored in /var/run/utmp. On current systems, this is really /run/utmp, and only has information for the current boot (/run is a tmpfs which loses its contents when the system is rebooted); but for the current boot, it is also accurate.
last reboot uses the information stored in /var/log/wtmp. The information stored there is also generally accurate, but the information you need might no longer be stored there: wtmp is rotated in many setups, typically monthly. This means that if the system’s current boot time is older than wtmp’s last rotation time, the information presented will be partial. In particular, last reboot ends up showing the last rotation time, not the system’s actual boot time. This is why last shows the time at which wtmp begins: that’s the time horizon for the information displayed by last.
When wtmp contains the last boot time, last reboot does show it:
$ last reboot | head -n 1
reboot system boot 5.10.0-8-amd64 Mon Sep 13 15:56 still running
$ who -b
system boot 2021-09-13 15:56
$ uptime
09:11:03 up 31 days, 17:15, 13 users, load average: 0.48, 0.34, 0.42 |
I am using the following 3 commands to check the latest time point when my computer is rebooted:
last reboot
who -b
uptimeThe result for last reboot is:
wtmp begins Sat Oct 9 04:49:27 2021The result for who -b is:
system boot 2018-01-11 20:52The result for uptime is:
22:49:01 up 1372 days, ...It seems that the result of uptime and who -b is consistent with each other, but inconsistent with that of last reboot.
I find this post Uptime and who -b are showing different times when the system was last booted on Linux, but it said his uptime and who -b is inconsistent with each other, different from my case.
| last reboot and who -b shows different results? |
Some/many (but not all) modern kernels add an offset to jiffies - it's a very large offset, basically it's 4294967295 - (300 * HZ)
The 300 * HZ is a 5 minute offset so that the kernel always tests jiffy rollover
So, for 300Hz that would be 4294877295
Subtracting that from the jiffies value, then dividing by HZ should produce the right result
4356505571 - 4294877295 = 6162827661628275 / 300 = 205427.587Which STILL doesn't match the values in the question
However, in the comments, the OP says that after 90 seconds, jiffies is 4294904295
4294904295 - 4294877295 = 2700027000 / 300 = 90.000To put that into a simple formula
uptime = (jiffies - (4294967295 - (300 * HZ))) / HZor
uptime = (jiffies - 4294967295) / HZ - 300Note: All my linux systems use the offset - except my OpenWRT routers - despite having kernel version 5.4 in the latest release, the jiffies to uptime relationship is simply as the OP expected:
uptime = jiffies / HZMost (all?) of this information was gleaned fromhttps://stackoverflow.com/a/63176716/10549313 - credit goes to @firo for that; and
and https://stackoverflow.com/a/33612184/10549313 - credit goes to @ZanLynxHowever, adding here probably makes sense too
|
System uptime is stored in /proc/uptime.
As you know, the Linux kernel has a jiffies variable which increments by each timer interrupt specified by the HZ parameter. I got the value ofHZ by the following command:
$ zcat /proc/config.gz | grep CONFIG_HZ=CONFIG_HZ=300In my machine, it's equal to 300. So I divided the jiffies given by /proc/timer_list by this number.
# cat /proc/timer_list | grep -E "^jiffies" | head -n1 && cat /proc/uptime jiffies: 4356505571
516409.13 1432145.01I was assumed to get the same number but it's remarkably different.
I mean 4356505571/300=14521685.23 should be really close to 516409.13, but it's not!
Is there any idea behind jiffies that I am not aware of?
| Why jiffies/HZ does not match uptime? |
If you are using Ubuntu
then add below lines in "/etc/rc0.d/S60umountroot" at the beginning.
Log="/var/log/uptime.log"
echo "$(date) $(/usr/bin/uptime)" >> "${Log}"or you can simply use logger
logger "UPTIME: $(uptime)"then it will gives details in /var/log/syslog or /var/log/messages
Note :- Please careful edit this file
If you are using CentOs, then do the same in "/etc/rc.d/rc0.d/S01halt",
but note that it should be added in beginning of the file.
|
I need to log PC uptime. How I can do this?
I use uptime for this and I will when ubuntu is shutdown write this command output in a file.
| write pc uptime in a file in shutdown |
the machine is remote/embed in a system.Sometimes the electricity is shut down. The internet connection is very slow Does the system have a clock and a battery in it?1 A lot of embedded systems don't. If not, this: Some other answers would say that the ntp server was launched after the reboot and so the system had to go backwards to set the time.Makes a lot of sense, although probably it's been up for 3 days not 5 (i.e. it went forward). You can confirm this by looking back through syslog -- something you've haven't mentioned, and which will confirm the actual time of the last boot. Unless because it's embedded you don't save logs, which returns us to the very likely scenario of a system without a clock: they don't have the correct time until ntp gets it. The time they do use will probably be in the past; I'm not sure what the mechanism is (maybe a filestamp).
1 If it does: how old is the battery? They do need to be replaced periodically.
|
I know this has been more or less asked before but I still don't have any answer.
I started to investigate why on my system (it is a remote machine) who -b and uptime gave different results (~3 days for one / 5 days for the other).
Some answers would say that maybe /var/run/utmp is corrupted. Some other answers would say that the ntp server was launched after the reboot and so the system had to go backwards to set the time.
Here are a few commands I have typed down :
ubuntu@arm:~$ sudo hwclock --show
Mon 25 Nov 2013 03:07:02 PM CET -0.464179 secondsubuntu@arm:~$ uptime
15:08:17 up 3 days, 53 min, 1 user, load average: 0.88, 0.51, 0.41ubuntu@arm:~$ date
Mon Nov 25 15:08:33 CET 2013ubuntu@arm:~$ who -b
system boot 2013-11-20 12:38ubuntu@arm:~$ last reboot
reboot system boot 3.7.10-x9 Wed Nov 20 12:38 - 15:08 (5+02:30)
reboot system boot 3.7.10-x9 Wed Nov 20 12:37 - 15:08 (5+02:31)
reboot system boot 3.7.10-x9 Thu Nov 7 14:26 - 12:36 (12+22:10)
reboot system boot 3.7.10-x9 Thu Nov 7 14:25 - 12:36 (12+22:11)
reboot system boot 3.7.10-x9 Thu Nov 7 14:23 - 12:36 (12+22:12)
reboot system boot 3.7.10-x9 Thu Nov 7 14:22 - 12:36 (12+22:14)
reboot system boot 3.7.10-x9 Tue Nov 5 14:58 - 14:22 (1+23:23)
reboot system boot 3.7.10-x9 Sat Nov 2 12:20 - 14:58 (3+02:37)
reboot system boot 3.7.10-x9 Sat Nov 2 12:20 - 12:20 (00:00) wtmp begins Sat Nov 2 12:20:00 2013Notes : the machine is remote/embed in a system. Sometimes the electricity is shut down. The internet connection is very slow (sim card)
Questions :
1) What does it mean when there are multiple lines for 1 boot ? I would expect all the lines to look like Nov 5, but on the 7th there are 4 lines at almost the same time and the end time is the same for all of them. I would expect 14:22-14:23 (00:01), 14:23-14:25 (00:02), ...
2) If the electricity is turned down and up again, does it count as a reboot ? How does it affect the internal time ? (ntp server stuff)
3) Is there a scenario one can trust for the 2 days difference between uptime and who -b ? My guts tell me that the file /var/run/utmp can't be corrupted/have permissions errors as no one else than the system use it.
Any help is grandly appreciated
Ref: Uptime and who -b are showing different times when the system was last booted on Linux
| last reboot/uptime/... strange behaviour |
You may get it for free from the output of last reboot:
$ last reboot
reboot system boot 4.14.81-i7 Sat Nov 17 23:25 still running
reboot system boot 4.14.80-i7 Fri Nov 16 09:16 - 15:49 (06:33)$ printf "On since: "; last reboot | grep "still running" | cut -c 40-56
On since: Sat Nov 17 23:25 $ printf "On since: " ; last reboot --time-format iso | grep "still running" | cut -c 40-49
On since: 2018-11-17Your uptime command might also have the -s option:
$ uptime -s
2018-11-17 23:25:23Since this format is acceptable to date -d, you can reformat the time however you wish like this::
$ date -d "$(uptime -s)" "+On since: %d:%m:%y"
On since: 17:11:18 |
I want to convert uptime to date DD:MM:YY without the | and I want to put a string like "the computer is on since 23-feb-16"
| Convert linux uptime to well format date |
Idle time is the sum of all your CPU/core idle times, while uptime is the wall-clock time your system has been up.
I'm guessing you have four CPUs/cores/threads.
|
I was testing out the linux api while working on something but got stuck on the following output.
[Abhii@localhost net]$ cat /proc/uptime
39135.53 149657.73As per specs the first number should be the Uptime and the second number should be the time system has stayed idle.
So why is the former less then latter ???
As an extra piece of info my version information
Linux version 3.5.2-3.fc17.x86_64 (mockbuild@) (gcc version 4.7.0 20120507 (Red Hat 4.7.0-5) (GCC) ) #1 SMP Tue Aug 21 19:06:52 UTC 2012 | System IDLE Time > System Uptime? |
It depends on the system you are talking about. For Linux-based systems, you probably are using uptime from procps, which reads the data from /proc/uptime.
To see this, read the source-code in its Git repository, e.g., uptime.c, which uses proc/sysinfo.c.
According to CentOS documents3.2.30. /proc/uptime
This file contains information detailing how long the system has been on since its last restart. The output of /proc/uptime is quite minimal:
350735.47 234388.90
The first number is the total number of seconds the system has been up. The second number is how much of that time the machine has spent idle, in seconds.But the source-code in uptime.c ignores the idle value. Because the system is powered on, I would expect it to reflect the elapsed time.
|
I was wondering how uptime is calculated.
Is it simply the difference between now and boot time? More specifically-- If I were to boot up, run for 5 minutes, and put the machine to sleep for a year; Upon resuming, would my uptime show 5 minutes, or 1 year and 5 minutes?
I find the verbiage in the man page a little vague on this point:uptime - Tell how long the system has been running. | How is uptime calculated? |
I have found the solution. I simply did not understand its syntax well enough. I just had to edit my ~/.i3/i3status.sh file. It is now:
#!/bin/sh/usr/bin/i3status -c $HOME/.i3status.conf | while :
do
read line
RAM=`free -kh | grep Mem | awk '{print $3}'`
TOTR=$(cat /proc/meminfo | grep MemT | sed 's/.*\://g' | sed 's/ *//g' | sed 's/kB//g')
TOT=$(octave --eval "$TOTR/1024^2" | sed 's/ans = *//g' | sed 's/$/G/g' ) # Put uptime
uptime=`uptime | awk '{print $3 " " $4}' | sed 's/,.*//'`
hour=$(echo $uptime | sed 's/\:.*//g')
min=$(echo $uptime | sed 's/.*\://g')
UP="$hour h $min m" # Compile C++ CPU prog and run it
g++ -o cpu.o $HOME/.i3/cpu.cpp
CPU=$(./cpu.o) printf "%s\n" "Up: $UP | CPU: $CPU% | RAM: $RAM/$TOT | $line"
doneThe most relevant lines to uptime are between # Put uptime and # Compile C++... and the final printf "%s\n"... command. My complete i3 configuration files can be found in this repository.
|
I would like to display uptime in common units (so not just in minutes if it is over an hour; also not just in seconds if it is over a minute; e.g., "1:02:30" for 1 hour, 2 minutes and 30 seconds would be my ideal time format) in my i3status bar. I have not even been able to find how to show uptime in the i3status bar in any units. I found this repo on GitHub that seemed to claim to do this but copying these configs gave me errors related to difficulty executing the status_command line in this repo's config. Namely the status_command line is:
status_command ~/.i3/i3status.sh ~/.i3/i3status.confguessing it only works with an older version of i3. Any ideas how to do this? here is my present ~/.i3status.conf file. My distribution is Gentoo Linux.
| How to display uptime in i3status bar? |
Edit: As @fpmurphy1 mentioned in a comment, there's no need for all the runlevel grepping below.
A simple last reboot -n 10 will do. last -xF | grep -e 'lvl 2' -e 'lvl 5' | head -10
last is mainly used to check when and for how long a certain user was logged in (also see lastlog for that), but the log file it uses (/var/log/wtmp by default) also logs system reboots and runlevel changes.
-x includes these runlevel changes in the output and -F prints the full date and time (instead of an abbreviated form).
The normal multi-user mode is usually runlevel 2, so we grep for that and extract the first (i.e. most recent) 10 results.
$ last -xF | grep 'lvl 2' | head -10
runlevel (to lvl 2) 4.6.3-040603-gen Sat Jul 16 08:41:02 2016 - Sat Jul 16 11:08:37 2016 (02:27)
runlevel (to lvl 2) 4.6.3-040603-gen Fri Jul 15 14:37:20 2016 - Fri Jul 15 20:58:40 2016 (06:21)
runlevel (to lvl 2) 4.6.3-040603-gen Thu Jul 14 22:50:43 2016 - Thu Jul 14 22:52:07 2016 (00:01)
runlevel (to lvl 2) 4.6.3-040603-gen Thu Jul 14 13:50:13 2016 - Thu Jul 14 22:50:12 2016 (08:59)
runlevel (to lvl 2) 4.6.3-040603-gen Tue Jul 12 13:17:37 2016 - Thu Jul 14 00:06:28 2016 (1+10:48)
runlevel (to lvl 2) 4.6.3-040603-gen Tue Jul 12 10:21:00 2016 - Tue Jul 12 11:07:47 2016 (00:46)
runlevel (to lvl 2) 4.6.3-040603-gen Mon Jul 11 21:56:36 2016 - Mon Jul 11 23:35:26 2016 (01:38)
runlevel (to lvl 2) 4.6.3-040603-gen Mon Jul 11 07:37:25 2016 - Mon Jul 11 09:25:13 2016 (01:47)
runlevel (to lvl 2) 4.6.3-040603-gen Sun Jul 10 16:40:55 2016 - Sun Jul 10 23:14:01 2016 (06:33)
runlevel (to lvl 2) 4.6.3-040603-gen Fri Jul 8 14:52:26 2016 - Sun Jul 10 13:13:59 2016 (1+22:21) |
How can I see when my PC was rebooted? I need to know the last 10 times.
| How can I see when my PC was rebooted? |
My solution
1. Create a very very short script
Just create a new file and rename it uptime.sh; then just copy this:
!#/bin/shecho "$(uptime -p)" > ~/.config/i3/uptimethis will append or write the output of the command uptime -p to a file which I chose to be in ~/.config/i3/uptime. The command uptime -p shows uptime in a pretty format.If done correctly the contents of your ~/.config/i3/uptime should be up x hours, x minutes.
Another command you can try is uptime -s which will show the date and time since your system was up.2. Create a cron job
Just execute crontab -e in the terminal then append this line:
* * * * * /home/user/path/to/uptime.shthis will execute the script every minute, therefore refreshing or overwriting the contents of uptime every minute. So that we can get the most recent uptime possible.
If you don't want the script to execute or to refresh the file every minute, you can replace * * * * * with @hourly for just an hourly refresh of uptime file.
3. Lastly, edit your i3status config file
Like this:
# uptime
read_file uptime {
color_good = "#ffffff"
format = "%content"
path = "/home/user/.config/i3/uptime"
}And that's it. Restart i3 and hopefully i3status uptime shows up pretty.
|
I'm trying to display my system uptime with i3status. This is what I have in my i3status.conf file:
read_file uptime {
format = "%title: %content"
path = "/proc/uptime"
}However the output is in seconds, as can be seen in this screenshot, which is obviously not ideal:Is there a way I am able to format this, to display for example in the format of:
DD:HH:MM:SS | Format the output of "read_file uptime" in i3status |
Assuming you just want all output in the terminal:
#!/bin/bashhosts_file=/path/to/file
username=youruserwhile read -r host; do
hostname=$(ssh "${username}@${host}" hostname)
ip_addr=$(ssh "${username}@${host}" hostname -I)
uptime=$(ssh "${username}@${host}" uptime)
echo
{
echo "Hostname:?$hostname"
echo "IP:?$ip_addr"
echo "uptime:?$uptime"
} | column -s\? -t
echo
done <"$hosts_file"This will loop through each line of your hosts_file, assigning the whole line to host. Then it will set the hostname, ip_addr, and uptime to the corresponding results on the remote machine. It will then echo those results in a columnized format.
| I am looking to build a script that will log in to multiple servers using a host file and run uptime, hostname -I and hostname
Script so far
echo"" ;
echo "hostname:" $(ssh $HOST hostname) ;
echo "IP:" $(ssh $HOST hostname -I) ;
echo "uptime" $(ssh $HOST uptime) ;
echo"" ;What would be the best way to accomplish my goal?
| uptime Script help [closed] |
I would do the whole test in AWK:
awk '$1 > (72 * 3600) { print "yes" }' /proc/uptimeIf you want to use that as a test, use the exit code:
if awk '{ exit ($1 < (72 * 3600)) }' /proc/uptime; then
echo Need to reboot
fiAWK evaluates ($1 < (72 * 3600)) as 0 if the comparison fails, 1 otherwise; 0 indicates success as an exit code, so we invert the condition.
If you’re using systemd, another approach would be to use a systemd timer, with OnBootSec=72h (see FelixJN’s answer for details).
|
I need to create a script that will execute daily (cron job), calculate the uptime of the system, and if that number is greater than 72 hours, reboot the system.
I am getting lost in converting the value of hours to something I can compare to 72. It returns me 6499.04: command not found
#!/bin/bash
if $(awk '{print $1}' /proc/uptime) / 3600 > 72 ; then
echo "yes"
fiThank you in advance for any help!
| How to check if uptime is greater than 72h? |
If your servers are in a trusted, secure network, all in one or just a few network segments, installing an old rwhod service and its clients (rwho and ruptime) might also fit the bill. In Debian, those services are still packaged and installable by just installing two packages (rwhod and rwho), so if your distribution has it available and it fits your requirements, it might be the easiest solution.
RHEL 7 (and probably distributions related to it) has both the service and the clients packaged as a single rwho package; RHEL 8 and newer don't seem to include that package any more.
rwhod will send out a broadcast packet once per minute, listing the logged-in users and the current uptime, and listens for other similar broadcasts; the rwho and ruptime commands will take the reports collected by rwhod and output a report of all hosts that have been broadcasting within the last 11 minutes. rwho lists the users logged in each broadcasting host according to the last report received; ruptime lists the uptime of each reporting host.
|
I have many linux servers which I would like to check uptime but I have to login to every one. Is this possible to check linux server running time without ssh login to it?
PS. My distributions are RHEL 7/8 and OL 8.
| System uptime without ssh login |
Depends on needs, but you have a few options. My personal choice is to use lvm mirroring on a root volume, and any other that is critical to my sanity (/home on my laptops and workstations).
As for backups, you could tarball up or rsync your stuff to a remote host, or if it's a bit simpler even use git (works wonders on /etc).
I used to just use mdadm to do mirror and stripes, and gave up and just use lvm since it's far easier to migrate things (swap drives, add drives, move to new host) than mdadm is.
|
I would like to set up my desktop computer (which is actually a server for the KVM guests I do my actual work in) to have a redundant root installation. If one drive dies I want to quickly get back to work without doing a full restore from backup, nor a system reinstall and reset all my settings and preferences.
I thought that the way to do this would be RAID1, but the deeper I dig into it, the more I realize that RAID1 is not a 'set-it-and-forget-it' solution. Oh, and I want it to be UEFI boot.
Last time I tried a software RAID1 install (which I set up using the Ubuntu Server installer), something got corrupted and I ended up with a GRUB rescue screen and could not for the life of me figure out how to get it to boot from the mirror drive. For all I know, the boot sector on both was corrupted due to the corruption replicating between drives. Obviously this defeats the purpose of having a RAID1 boot for the purpose of decreased downtime. I was thinking that maybe I should put the EFI partition on a USB drive and keep it backed up for quick and easy replacement (while having the root partition in RAID1), but I am worried that I might now always know then the EFI partition has changed and therefore will not know when to back it up.
I was also thinking to do ZFS-on-root, in the thought that the bitrot protection and snapshotting might be more useful in preventing situations like the one above. But it seems that ZFS on root is not recommended for Ubuntu, and the status of ZFS on Linux in general seems to be in question now due to a certain Linux Kernel programmer's stated lack of tolerance for ZFS. I wonder if this might be a good approach but I know nothing about this whole MAAS thing and have no idea whether it is relevant to my use case.
The last thing I was thinking was to just do a regular one-drive install and then every week or so dd it to a spare drive, so that if disaster strikes I can at least recover my settings and installation from a week ago or less. But wouldn't dding an SSD every week be really hard on it?
I have found countless tutorials about RAID and ZFS, but so far have not found anything that clearly explains to pros and cons of my options with respect to the goal stated above. Advice or links to explanations would be greatly appreciated!
| Most ironclad way to make root installation redundant and maximize uptime? RAID, ZFS or something else? |
If I try this:
$ echo "167h58m10.586582048s" | awk -F '[hm.]' '{ print ($1 * 3600) + ($2 * 60) + $3 }'
604690It works great.
Thanks @steeldriver. I didn't know about that.
I found this good article about Field Separators in awk.
|
I'm receiving an uptime in this format:
167h58m10.586582048sI want to transform it to seconds and discard the fraction part.
I know awk could do that if only the received string had the same separator. That's not the case.
How could I convert that to seconds?
| Convert string time to seconds |
On Debian 9 there are files being executed upon ssh'ing into the server in the directory:
/etc/update-motd.d/All files in it will be executed upon successful ssh'ing if having an executable bit set.
So in this case, first list all the files in it:
ls -l /etc/update-motd.d/and then investigating the contents with cat.
In my case, there was only one file named:
10-unamewith contents:
#!/bin/sh
uname -snrvmwhich is what I was looking for.I simply changed the line:uname -snrvmto:uptime --prettyAnd renamed the script to:
00-uptimeBoth the uname message is gone, and uptime gets displayed now.When ssh'ing into the server I now see:up 6 days, 12 hours, 15 minutes
No mail.Note:
It might be wise to set immutable attribute to the file preventing it from being changed with:
sudo chattr +i /etc/update-motd.d/00-uptime |
I would love to get rid of this uname message when ssh'ing into the Debian 9 machine:Linux backup-server 4.9.0-5-amd64 #1 SMP Debian 4.9.65-3+deb9u2 (2018-01-04) x86_64This line I would like to keep:No mail.I tried:
ssh -q ...and setting:PrintLastLog noin the:
/etc/ssh/sshd_configThen, I deleted the contents of this file, completely:
/etc/motdbecause I don't care about it.
As a bonus, if possible I would like to see the uptime --pretty when ssh'ing into the Debian server.
| How to suppress Debian uname message when ssh'ing into the machine? Plus changing it to something else, if possible |
There is quite a good walkthrough here. Essentially the tool you're wanting to use is virt-install, which you should already have if you have installed everything needed for QEMU-KVM. Here's the most relevant section.6. Creating a new Guest VM using virt-install
virt-install tool is used to create the VM. This tool can be used in
both interactive or non-interactive mode.
In the following example, I passed all the required values to create
an VM as command line parameters to the virt-install command.# virt-install \
-n myRHELVM1 \
--description "Test VM with RHEL 6" \
--os-type=Linux \
--os-variant=rhel6 \
--ram=2048 \
--vcpus=2 \
--disk path=/var/lib/libvirt/images/myRHELVM1.img,bus=virtio,size=10 \
--graphics none \
--cdrom /var/rhel-server-6.5-x86_64-dvd.iso \
--network bridge:br0In the above virt-install command the parameters have the following meaning:n: Name of your virtual machine
description: Some valid description about your VM.
For example: Application server, database server, web server, etc.
os-type: OS type can be Linux, Solaris, Unix or Windows.
os-variant: Distribution type for the above os-type. For example, for linux, it can be rhel6, centos6, ubuntu14, suse11, fedora6 , etc.
For windows, this can be win2k, win2k8, win8, win7
ram: Memory for the VM in MB
vcpu: Total number of virtual CPUs for the VM.
disk path=/var/lib/libvirt/images/myRHELVM1.img,bus=virtio,size=10: Path where the VM image files is stored. Size in GB. In this example,
this VM image file is 10GB.
graphics none: This instructs virt-install to use a text console on VM serial port instead of graphical VNC window. If you have the
xmanager set up, then you can ignore this parameter.
cdrom: Indicates the location of installation image. You can specify the NFS or http installation location (instead of –-cdrom). For
example: --location=http://.com/pub/rhel6/x86_64/*
network bridge:br0: This example uses bridged adapter br0. It is also possible to create your own network on any specific port instead of bridged adapter.
If you want to use the NAT then use something like
below for the network parameter with the virtual network name known as
VMnetwork1. All the network configuration files are located under
/etc/libvirt/qemu/networks/ for the virtual machines. For example:
–-network network=VMnetwork1 |
It looks like that you cannot create a brand new VM with virsh unless you already have a working XML file.
I have just installed all the needed bits for QEMU-KVM to work, and need now to create my very first VM.
How to?
Hint: I don't have graphics!
| How to create a VM from scratch with virsh? |
Qemu is the lowest level that emulates processor and peripherals. KVM is to accelerate it if the CPU has VT enabled. Libvirt provides a daemon and client to manipulate VMs for convenience. See also Difference between KVM and QEMU on Server Fault.
|
I'm trying to understand how all the components of the VM ecosystem fit together.
What's the difference between:KVM
QEMU
libvirtWhich is controlled by virsh and virt-install?
This comment says that libvirt is an abstraction ontop of QEMU, which is an abstraction ontop of KVM. However the official QEMU docs say that QEMU is a processor emulator, which sounds like the lowest level component.
| What's the difference between KVM, QEMU and libvirt? |
From the man page:-
virsh list --autostartshould do it.
|
In virsh how do I see which domains are marked as autostart? virsh list does not show which domains are marked as autostart.
| virsh, how to list autostart domains? |
virsh destroy, from man virsh
Immediately terminate the domain domain.
This doesn't give the domain OS any chance to react,
and it's the equivalent of ripping the power cord out on a physical machine. |
I'm trying to find the corresponding command to the buttons in virt-manager,
I read about virsh help domain and I found start, shutdown and reset etc. But the one for Force Off is missing.
Anyone know what that is?
| What commands in virsh corresponds to "Force Off" button in virt-manager? |
Seems like an event for the power button wasn't created automatically, not sure why?
Created a new event handler here:
sudo nano /etc/acpi/events/powerbtn
With these parameters:
event=button/power
action=/sbin/poweroffThen restarted the service:
sudo service acpid restart
Now I'm able to shutdown the guest!
|
I am running Ubuntu 18.04 (desktop) in a VM using Debian 9 and KVM as the hypervisor but running virsh shutdown BS-MS01 I get a message saying the domain is shutting down but the VM is actually still sat on the login screen.
I have confirmed acpid is installed and running on the guest:
ms01admin@BS-MS01:~$ sudo service acpid status
● acpid.service - ACPI event daemon
Loaded: loaded (/lib/systemd/system/acpid.service; disabled; vendor preset: e
Active: active (running) since Sat 2019-02-16 20:33:52 GMT; 2h 17min ago
Main PID: 716 (acpid)
Tasks: 1 (limit: 4614)
CGroup: /system.slice/acpid.service
└─716 /usr/sbin/acpidThe VM has been created with </acpi> in the xml too:
<domain type='kvm' xmlns:qemu='http://libvirt.org/schemas/domain/qemu/1.0'>
<name>BS-MS01</name>
<uuid>8e94c247-bf28-455f-bdee-c64f0a1c9404</uuid>
<title>BS-MS01</title>
<description>Main media server.</description>
<memory unit='KiB'>4194304</memory>
<currentMemory unit='KiB'>4194304</currentMemory>
<vcpu placement='static'>8</vcpu>
<os>
<type arch='x86_64' machine='pc-q35-2.8'>hvm</type>
<loader readonly='yes' type='pflash'>/usr/share/OVMF/OVMF_CODE.fd</loader>
<nvram>/var/lib/libvirt/qemu/nvram/BS-MS01_VARS.fd</nvram>
<boot dev='hd'/>
<bootmenu enable='no'/>
</os>
<features>
<acpi/>
<apic/>
<vmport state='off'/>
</features>
<cpu mode='custom' match='exact'>
<model fallback='allow'>Haswell-noTSX</model>
</cpu>
<clock offset='utc'>
<timer name='rtc' tickpolicy='catchup'/>
<timer name='pit' tickpolicy='delay'/>
<timer name='hpet' present='no'/>
</clock>
<on_poweroff>destroy</on_poweroff>
<on_reboot>restart</on_reboot>
<on_crash>restart</on_crash>
<pm>
<suspend-to-mem enabled='no'/>
<suspend-to-disk enabled='no'/>
</pm>
<devices>
<emulator>/usr/bin/kvm</emulator>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2'/>
<source file='/storage/vm/hdd/bsms01.qcow2'/>
<target dev='vda' bus='virtio'/>
<address type='pci' domain='0x0000' bus='0x05' slot='0x00' function='0x0'/>
</disk>
<disk type='file' device='cdrom'>
<driver name='qemu' type='raw'/>
<target dev='sda' bus='sata'/>
<readonly/>
<address type='drive' controller='0' bus='0' target='0' unit='0'/>
</disk>
<controller type='usb' index='0' model='nec-xhci'>
<address type='pci' domain='0x0000' bus='0x04' slot='0x00' function='0x0'/>
</controller>
<controller type='sata' index='0'>
<address type='pci' domain='0x0000' bus='0x00' slot='0x1f' function='0x2'/>
</controller>
<controller type='pci' index='0' model='pcie-root'/>
<controller type='pci' index='1' model='pcie-root-port'>
<model name='ioh3420'/>
<target chassis='1' port='0x8'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x0' multifunction='on'/>
</controller>
<controller type='pci' index='2' model='dmi-to-pci-bridge'>
<model name='i82801b11-bridge'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x1e' function='0x0'/>
</controller>
<controller type='pci' index='3' model='pci-bridge'>
<model name='pci-bridge'/>
<target chassisNr='3'/>
<address type='pci' domain='0x0000' bus='0x02' slot='0x00' function='0x0'/>
</controller>
<controller type='pci' index='4' model='pcie-root-port'>
<model name='ioh3420'/>
<target chassis='4' port='0x9'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
</controller>
<controller type='pci' index='5' model='pcie-root-port'>
<model name='ioh3420'/>
<target chassis='5' port='0xa'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>
</controller>
<controller type='pci' index='6' model='pcie-root-port'>
<model name='ioh3420'/>
<target chassis='6' port='0xb'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x3'/>
</controller>
<controller type='pci' index='7' model='pcie-root-port'>
<model name='ioh3420'/>
<target chassis='7' port='0xc'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x4'/>
</controller>
<controller type='pci' index='8' model='pcie-root-port'>
<model name='ioh3420'/>
<target chassis='8' port='0xd'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x5'/>
</controller>
<controller type='pci' index='9' model='pcie-root-port'>
<model name='ioh3420'/>
<target chassis='9' port='0xe'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x6'/>
</controller>
<interface type='bridge'>
<mac address='52:54:00:40:b9:20'/>
<source bridge='br0'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x01' slot='0x00' function='0x0'/>
</interface>
<input type='mouse' bus='ps2'/>
<input type='keyboard' bus='ps2'/>
<sound model='ich6'>
<address type='pci' domain='0x0000' bus='0x03' slot='0x01' function='0x0'/>
</sound>
<hostdev mode='subsystem' type='pci' managed='yes'>
<source>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
</source>
<address type='pci' domain='0x0000' bus='0x06' slot='0x00' function='0x0'/>
</hostdev>
<hostdev mode='subsystem' type='pci' managed='yes'>
<source>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
</source>
<address type='pci' domain='0x0000' bus='0x07' slot='0x00' function='0x0'/>
</hostdev>
<redirdev bus='usb' type='spicevmc'>
<address type='usb' bus='0' port='1'/>
</redirdev>
<redirdev bus='usb' type='spicevmc'>
<address type='usb' bus='0' port='2'/>
</redirdev>
<memballoon model='virtio'>
<address type='pci' domain='0x0000' bus='0x08' slot='0x00' function='0x0'/>
</memballoon>
</devices>
<qemu:commandline>
<qemu:arg value='-cpu'/>
<qemu:arg value='host,hv_time,kvm=off,hv_vendor_id=null'/>
</qemu:commandline>
</domain>I've even added acpi=force to grub but have not had any luck getting it to work and I've run out of ideas.
Anyone got any ideas?
| Unable to shutdown Ubuntu 18.04 guest using virsh-shutdown |
You must have used different credentials when using virsh and virt-manager. Do everything under your user, or at least the same user every time instead. virt-manager and virsh are interfaces to the same libvirt VM database, but the user context makes a difference, so if you want to manage the same set of VMs, always use the same user with both utilities.
| here's a question for you that's been driving me round the bend. I've managed to find plenty of resource from folk that want to do the opposite from me i.e see a machine they created using virsh in virt-manager.
However, I have a couple of VMs that I created through virt-manager that I now need to control using virsh.
When I use e.g. virsh start <vm-name> it fails claiming the domain isn't found.
virsh list --all returns nothing.
If it makes any difference, the storage volumes I created have been moved to a sub-directory on my /home partition.
Also, libvirtd is definitely running and the machines can still be controlled and accessed with virt-manager.
Any and all help would be greatly appreciated.
| Using virsh to control VMs created in virt-manager [closed] |
A storage pool of type dir is a directory path. The only meaningful value is the directory path itself so all other parameters are ignored. In your example, /var/lib/libvirt/rhpol_virsh is a location in your filesystem that will be mapped to the storage pool rhpol_virsh.
Another way of viewing this command, which I prefer, is by named parameter rather than positional parameter. This also defines your pool as rhpol_virsh as being part of your filesystem starting at /var/lib/libvirt/rhpol_virsh:
virsh pool-define-as rhpol_virsh --type dir --target /var/lib/libvirt/rhpol_virshAt the risk of over complicating matters, but trying to answer your comment questions, the man page defines positional parameters as follows:
pool-define-as name --print-xml type [source-host] [source-path] [source-dev] [source-name] [<target>] [--source-format format]Since the pool definition doesn't need anything except target we need - placeholders to get to the target. Thus pool-define-as rhpol_virsh - - - - /var/lib/libvirt/rhpol_virsh.
Once you have defined the storage pool you need to start it:
virsh pool-autostart rhpol_virsh # Start on boot
virsh pool-start rhpol_virsh # Start nowYou can see which storage pools are defined, and their status, with virsh pool-list. If you add something to a storage pool you may need to tell the libvirt suite that the pool contents need refreshing:
virsh pool-list | awk '/active/{print$1}' | xargs -n1 virsh pool-refresh |
I am running CentOS 7 and was following a chapter in a book dealing with virtualization and creating storage pools. I successfully ran the following command, but I'm not sure what setting - - - - as the sourcepath actually does.
virsh pool-define-as rhpol_virsh dir - - - - /var/lib/libvirt/rhpol_virshDescription of command: Define the storage pool as type "dir" with the source path "----" and target /var/lib/libvirt/rhpol_virsh directory
I read the man pages and googled this topic, but I didn't find an explanation. Can someone point me in the right direction?
| virsh and creating storage pools - What is sourcepath "- - - -" |
I frequently use multiple "consoles" on my VMs - one for an interactive console showing the boot-up and ending with a login prompt, and another to log all of that to a text file (usually /var/lib/libvirt/consoles/<domain>.log)
I don't know if you can have multiple interactive "consoles" in a VM, but you can add as many serial ports as you like, and then run getty on them in the VM for the login prompt.
These serial ports in the VM can be connected to, e.g., a file, or a socket, or a TCP port on the host that speaks telnet protocol. Easiest to work with is probably a telnet port.
e.g. to add a serial ttyS1 serial port which can be accessed via telnet, save the following XML fragment to /tmp/serial1.xml:
<serial type='tcp'>
<source mode='bind' host='127.0.0.1' service='4555' tls='no'/>
<protocol type='telnet'/>
<target port='1'/>
<alias name='serial1'/>
</serial>Then run virsh attach-device --config <domain> /tmp/serial1.xml.
That will add a serial port device to the VM, which will be activated the next time the VM restarts. (There may be some way to add it as a hot-pluggable USB device rather than a non-USB serial port, and avoid the need to restart the VM. I've never cared enough to find out).
After the VM has rebooted, run a getty on the port. e.g. with sysvinit, edit /etc/inittab and run telinit q.
With systemd:
systemctl enable [emailprotected]
systemctl start [emailprotected]To connect to the VM's serial port from the KVM host, run telnet 127.0.0.1 4555.
You can create as many serial ports as you like, each listening on a different port. Just change the tcp port number (service=), target port, and alias name in the XML fragment.
If you need to access it from another machine, you can make it listen on a different IP address (although you probably want tls='yes' in that case, and use a tls-enabled telnet client to connect, which will require setting up a certificate for qemu to use).
For example, I added two serial ports to a Debian Stretch VM:
First, ttyS1 on localhost:4555
$ telnet localhost 4555
Trying 127.0.0.1...
Connected to localhost.mydomain.
Escape character is '^]'.Debian GNU/Linux 9 stretch ttyS1stretch login:
telnet> quit
Connection closed.Then ttyS2 on localhost:4556
$ telnet localhost 4556
Trying 127.0.0.1...
Connected to localhost.mydomain.
Escape character is '^]'.Debian GNU/Linux 9 stretch ttyS2stretch login:
telnet> quit
Connection closed. |
I have a serial console working for a centos7 guest without graphics, which I access with virsh console vm. The guest has the appropriate console=ttyS0,115200n8 kernel command line parameter for it.
Is it possible to configure additional consoles, so that I can say virsh console vm --devname vc1 and get a login prompt?
Instinctively, I was thinking of connecting somehow to the character devices of the guest's first 6 virtual consoles; I've looked into libvirt domain format and virtio-serial as it seemed I should go in that direction, but couldn't get it to work.
Background:
We had network issues which took a significant amount of time to fix, during which we needed one team member to work on network issues and the other to continue his work on the VM uninterrupted, thus the need for multiple consoles under no networking.
I am aware that having
<graphics type='vnc' port='5900' autoport='yes' listen='127.0.0.1'>
<listen type='address' address='127.0.0.1'/>
</graphics>enables VNC access with 6 virtual terminals, I was simply wondering if it is possible to have such 6 virtual terminals via the virsh console <domain> --device <device> syntax in any reasonable way, simply because virsh console is far more convenient.
Software:
# cat /etc/fedora-release # host
Fedora release 24 (Twenty Four)
# virsh --version
1.3.3.3
# qemu-system-x86_64 --version
QEMU emulator version 2.6.2 (qemu-2.6.2-8.fc24), Copyright (c) 2003-2008 Fabrice Bellard# cat /etc/centos-release # guest
CentOS Linux release 7.3.1611 (Core) | Multiple virsh/kvm guest consoles without graphics |
What you're using isn't KVM directly, but a management library called libvirt.
You can specify a user which will have access to libvirt's setup (and thus creating VMs and pretty much running virsh commands) by adding the users to the libvirtd and kvm groups on the host.
You can also use policykit to manage access, the procedure is described in the libvirt Wiki: SSHPolicyKitSetup | Libvirt Wiki
|
In a debian host with many users, I want to allow different users to create their own VMs, completely independent of each other.
The closest relevant (non-root) way I have seen in guides is by connecting to the qemu:///system hypervisor . This is the system hypervisor which is shared among all users. What is more the disk image file will be owned by root (or kvm) user, meaning that the whole filesystem path to the location of the disk image file must be world readable.
For the above and other reasons I want to run my VMs purely and completely as non root user. That is as qemu:///session . So the main question is how do I do that? Are there any guides I could use?
I went as far as trying to create new virtual bridge iface, but even though I am member of the netdev group I get "permission denied" errors when I do the following:
virsh -c qemu:///session net-create /etc/libvirt/qemu/networks/mynet.xmlnote than mynet.xml is just like default network but at a different subnet.
| how can I create a KVM guest 100% as a non root user? |
Old answer.:
May you take pkexec out of the script? Try create next script where you paste your code (without pkexec) and execute him via pkexec from your script.
your script: #!/bin/bash pkexec ./new_script
new script: #!/bin/bash your command:
Edit.: New Answer
After your conversation with @Thrig, I guess what you are going to do.
You want to run both programs on root permissions without double authentication (only once). These two programs are: "virsh" and "gnome-boxes". My previous (above) solution is ok, but not in this case. You wrote to @Thrig that you are considering using "sudo". Why not use "pkexec" and "sudo" together. With the proper completion of "/ etc / sudoers" you will not need to authenticate when you use the "sudo" command in the script. I let myself improve your idea. I hope you like it. I will describe everything step by step.
1. Create three scripts:
a) main.sh - set up the connection, destroy the connection, run gnome-boxes. everything as root
b) net.sh - execute the order
c) die.sh - execute the order
a)
#!/Bin/bash
sudo /home/ham/..your..path../net.sh && pkexec /usr/bin/gnome-boxes;
sudo /home/ham/..your..path../die.sh;
exitwhy that? description of operators
b)
#!/Bin/bash
virsh net-start defaultc)
#!/Bin/bash
virsh net-destroy default2. Edit the "sudoers" file to make the script: b) c) run with root privileges:
$ sudo nano /etc/sudoers
%sudo ALL=(root) NOPASSWD: /home/..your..path../net.sh
%sudo ALL=(root) NOPASSWD: /home/..your..path../die.sh 3. Change the owner of the scripts b) c) to root:
$ sudo chown 700 /home/ham/..your..path../net.sh
$ sudo chown 700 /home/ham/..your..path../die.sh;4. Create a rule in polkit for gnome-boxes. The answer: "how to do it?" is here: simple_polkit_rule
5. Edit files:org.gnome.Boxes.service
Exec=/home/..your..path../start.sh
org.gnome.Boxes.desktop
Exec=/home/..your..path../start.sh6. Now run the gnome-boxes application by clicking on its shortcut icon. Finished. From myself I added auto turn off connection when you close the gnome-boxes application.
|
Someone could answer me how make one prompt via pkexec when I've to use two command with authentication?
My easy sample script:
pkexec virsh net-start default;
pkexec "/home/user/program";I'm new in linux environmen,
Thanks :)
| One prompt pkexec - two command |
So, it turns out that specifying your boot device with --cdrom /path/to/bootmedia.iso can be problematic when it comes to viewing output during boot up. Trying to install again, I noticed this warning pop up before the Starting install... text:WARNING CDROM media does not print to the text console by default, so
you likely will not see text install output. You might want to use
--location. See the man page for examples of using --location with CDROM mediaI searched for this warning and found suggestions for adding the following to the virt-install args:
--location /path/to/bootmedia.iso en lieu of --cdrom
and --extra-args console=ttyS0.
After making these two changes, everything worked. The complete working install command is as follows:
virt-install \
-n ApacheServer \
--description "CENTOS7 for Apache Server" \
--os-type=Linux \
--os-variant=rhel6 \
--ram=2048 \
--vcpus=1 \
--disk path=/var/lib/libvirt/images/CentOS7-Apache.img,bus=virtio,size=10 \
--graphics none \
--console pty,target_type=serial \
--location /home/server/Downloads/CentOS-7-x86_64-Minimal-1810.iso \
--network bridge:virbr0 \
--extra-args console=ttyS0 |
I'm having an issue with viewing output from a virtual machine installed via virt-install.
I first used this method, but it left me with the following immediately after running:
Starting install...
Connected to domain ApacheServer
Escape character is ^]It sits here forever and no input is accepted into the terminal at this point. After some googling around the web, I ended up destroying/deleting my guest, and starting over with the install, but this time, I had added
--console pty,target_type=serial to the arguments being passed to virt-install. For some clarity, below is the complete install command I used last:
virt-install \
-n ApacheServer \
--description "CENTOS7 for Apache Server" \
--os-type=Linux \
--os-variant=rhel6 \
--ram=2048 \
--vcpus=1 \
--disk path=/var/lib/libvirt/images/CentOS7-Apache.img,bus=virtio,size=10 \
--graphics none \
--console pty,target_type=serial \
--cdrom /home/server/Downloads/CentOS-7-x86_64-Minimal-1810.iso \
--network bridge:virbr0This doesn't change anything for me. I am still stuck at Escape character is ^] after the install. I even closed this console window out, and tried to get into the guest via $ virsh console ApacheServer. This leaves me with:
Connected to domain ApacheServer
Escape character is ^]
error: operation failed: Active console session exists for this domainMy current expectation is that after the install, or after issuing the virsh console <domain name> command, I should see the console/terminal output that the guest is putting out.
| virsh: Connected to domain <name> Escape character is ^] |
One can delete a pool without VolumeGroup like this:
The files are stored in
/etc/libvirt/storageas XML files. Just delete them.
|
My virsh version
0.9.12.3I created a Volume Group Pool via virsh.
virsh pool-define-as vg1 logical --source-name vg --target /dev/vgBad thing is, that /dev/vg does not exist, I made a typo.
I tried to delete the pool by
virsh pool-delete vgwhich resulted in
error: Failed to delete pool vg1
error: internal error Child process (/sbin/vgremove -f vg) unexpected exit status 5: Volume group "vg" not foundso how do I remove this misconfigured pool?
| How to delete a virsh pool without volumegroup? |
You don't use port 2 of vnc console on vmname virtual machine, but you use 5902 port. You need to add 5900 to each output of vncdisplay command if you don't set up VNC port directly in virtual machine settings.
To edit virtual machine configuration use edit command:
edit vmnameAnd edit line like this:
<graphics type='vnc' port='5950' autoport='no' listen='0.0.0.0' passwd='password'>You need to restart (stop and start again, not reboot) virtual machine to apply configuration changes.
|
Currently I have a virtual machine running, and I can see that with:
# virsh list
Id Name State
----------------------------------------------------
1 vmname runningNow I want to VNC into the machine, so I check the port:
# virsh vncdisplay 1
127.0.0.1:2Port seems to be 2, but I want to change it to e.g. 5000. How do I do that?
| How do you change KVM VNC port at runtime, from the command line? |
Example based on comments by myself and @fra-san:
(I use a mixture of ZFS zvols, qcow2 and raw files for my VMs)
# for vm in $(virsh list --all --name) ; do
echo "$vm:"
virsh dumpxml "$vm" | xmlstarlet sel -t -m '/domain/devices/disk' -m 'source/@*' -v '.' -n
echo
done
debian10:
/dev/zvol/exp/debian10debian9:
/dev/zvol/exp/volumes/debian9freebsd:
/var/lib/libvirt/images/FreeBSD-10.2-RELEASE-amd64.qcow2stretch:
/dev/zvol/exp/stretch
/var/lib/libvirt/ISO-Images/debian-9-stretch/debian-9.13.0-amd64-DVD-1.isoztest:
/dev/zvol/exp/volumes/ztest
/var/lib/libvirt/ztest/disk01
/var/lib/libvirt/ztest/disk02
/var/lib/libvirt/ztest/disk03
/var/lib/libvirt/ztest/disk04
/var/lib/libvirt/ztest/disk05
/var/lib/libvirt/ztest/disk06
/var/lib/libvirt/ztest/disk07
/var/lib/libvirt/ztest/disk08
/var/lib/libvirt/ztest/disk09
/var/lib/libvirt/ztest/disk10
/var/lib/libvirt/ztest/disk11
/var/lib/libvirt/ztest/disk12
/var/lib/libvirt/ztest/disk13
/var/lib/libvirt/ztest/disk14Note the ISO image for the "stretch" VM. You may want to exclude things like that from your backups. Or detach all CD-ROM/DVD images from VMs before extracting the list of attached virtual disks.
The ztest VM has a lot of virtual disks (mostly ~200MB, some 1GB each) because it's the VM I use for testing ZFS upgrades (incl. kernel compatibility with dkms module packages) and to experiment with ZFS commands before I use them on real systems. I also use it for testing btrfs, LVM, mdadm, and other disk-related stuff.Another alternative is to use xml2 instead of xmlstarlet. It's a lot simpler than xmlstarlet, and more suited to "hacky" solutions with grep and awk and sed. It parses XML and converts it to a line-oriented format suitable for use with line-oriented tools.
for vm in $(virsh list --all --name) ; do
echo "$vm:"
virsh dumpxml "$vm" |
xml2 |
awk -F= '/^\/domain\/devices\/disk\/source\/@(file|dev)/ {print $2}'
echo
doneUnfortunately, xml2 seems to be abandonware these days. You can still find it in some distros (e.g. apt-get install xml2 on Debian) but the upstream seems to have vanished. It's old and unmaintained and doesn't support utf8 (and could probably be replaced with 5 or 10 lines of perl or python code). However, it's still useful for some tasks. If you need to compile it from source yourself, see my question where, oh where, has xml2 gone?BTW, you said "... so I have some backups while doing in place OS upgrade of the KVM hosts" - that's one of the things that snapshots are good for. You can do snapshots with ZVOLs, qcow2 files, and LVM. btrfs also supports snapshots but not for individual files (and if you're using btrfs for VM images, you're probably using raw or qcow2 files for the virtual disks)
|
Searching for a good way to export all VMs from KVM nodes so I have some backups while doing in place OS upgrade of the KVM hosts.
So far, I am using a hacky bash oneliner in order to dump all VMs as xml and list their disk paths for copying purposes:
for vm in $(virsh list --all | egrep -v "ID|---" | awk '{print $2}'); do virsh dumpxml "$vm" > "/root/vm/$vm.xml"; virsh domblklist "$vm" | grep '/' | awk '{print $2}' >> /root/vm/vm_disks.lst; doneThis works well, but virsh only does "human" output AFAIK so I have to grep/awk my way around the output which is not very reliable IMO.
Is there any clean way to achieve this without the need of a python script with libvirt ?
Best regards.
| How to export *all* VMs from KVM host |
The updates in CentOS 7.7 include an update to QEMU which needs a new package to be able to start QEMU/KVM virtual machines.
# yum install libvirt-daemon-driver-qemuThen the virtual machines can be started right away (no reboot necessary):
# systemctl restart libvirtd
# virsh list
Id Name State
----------------------------------------------------
1 mygreatvm running
2 mygreatvm2 running
3 mygreatvm3 runningSome CentOS hypervisors might have this package already installed; there will be no failures on these machines but the package was not necessary in the past.
|
After an automatic update of CentOS to version 7.7 on Sep 17 2019 my QEMU/KVM virtual machines do not start when I reboot the hypervisor server.
Trying to start the VM by hand gives this error:
# virsh start mygreatvm
error: failed to connect to the hypervisor
error: no connection driver available for <null>Trying to list currently defined VMs (the VMs in questions are set to start by default (autostart) on every boot so they should at least appear here):
# virsh list
error: failed to connect to the hypervisor
error: no connection driver available for <null>There are no error messages in system logs and neither in /var/log/libvirt/qemu/*.log. The libvirt daemon seems to run fine and does not complain about the non-started servers in /etc/libvirt/qemu/autostart/*xml:
# systemctl status libvirtd
● libvirtd.service - Virtualization daemon
Loaded: loaded (/usr/lib/systemd/system/libvirtd.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2019-09-18 16:42:30 UTC; 2min 49s ago
Docs: man:libvirtd(8)
https://libvirt.org
Main PID: 1817 (libvirtd)
Tasks: 16 (limit: 32768)
CGroup: /system.slice/libvirtd.service
└─1817 /usr/sbin/libvirtd
Sep 18 16:42:30 server systemd[1]: Starting Virtualization daemon...
Sep 18 16:42:30 server systemd[1]: Started Virtualization daemon. | Why does my QEMU/KVM virtual machine not start after CentOS 7.7 update? |
If you create the new image file in advance (e.g., using qemu-img create -f qcow2 -b <backing file> <new image name>) you could mount that drive as a loop device, then modify the files, unmount it and start the virtual machine. Mounting can be a little tricky at times since you have to skip past the partition table and the like.
Probably easier than trying to mount it yourself you can use libguestfs for many such tasks (http://libguestfs.org/) then probably you could use the virt-edit command to modify the files you want.
|
I have taken a snapshot recently to assist me build VMs quickly with the operating system I desire (through virsh), however, every time I build a VM, I would like to modify few files inside the img file before assigning the qemu img file to the VM such as, for example, the /etc/sysconfig/network-scripts/ifcfg-eth0 file and the shadow file. Is this possible through command line? I can do this through VNC if I assign the img file to the VM and then log into VNC to apply my changes, but I was wondering if there's a quick shell solution to achieve this.
Any suggestion would be greatly appreciated!
| Modifying files inside a snapshot (qemu img file) |
I finally figured it out!
So this is what virt-install will do by default:
sudo virt-install --network network=default,model=e1000,mac=00:11:22:33:44:55And the equivalent with qemu-system-x86_64 would be:
INTERFACE_NAME="$(sudo cat /var/lib/libvirt/dnsmasq/default.conf | grep "^interface=" | cut -d'=' -f2-)"
sudo qemu-system-x86_64 -net nic,model=e1000,macaddr=00:11:22:33:44:55 -net bridge,br=${INTERFACE_NAME}I would advise to make sure the default network is active first:
if ! sudo virsh net-list | grep default | grep --quiet active; then
sudo virsh net-start default
fiNote: The whole default network thing is provided by the package libvirt-daemon-config-network (at least on Fedora).
From the qemu man page:
-net nic[,netdev=nd][,macaddr=mac][,model=type] [,name=name][,addr=addr][,vectors=v]
Legacy option to configure or create an on-board (or machine default) Network Interface Card(NIC) and connect it either to the emulated hub with ID 0 (i.e. the default hub), or to the netdev nd. If model is omitted,
then the default NIC model associated with the machine type is used. Note that the default NIC model may change in future QEMU releases, so it is highly recommended to always specify a model. Optionally, the MAC ad‐
dress can be changed to mac, the device address set to addr (PCI cards only), and a name can be assigned for use in monitor commands. Optionally, for PCI cards, you can specify the number v of MSI-X vectors that the
card should have; this option currently only affects virtio cards; set v = 0 to disable MSI-X. If no -net option is specified, a single NIC is created. QEMU can emulate several different models of network card. Use
-net nic,model=help for a list of available devices for your target. -net user|tap|bridge|socket|l2tpv3|vde[,...][,name=name]
Configure a host network backend (with the options corresponding to the same -netdev option) and connect it to the emulated hub 0 (the default hub). Use name to specify the name of the hub port.From the virt-install man page:
NETWORKING OPTIONS
-w, --network
Syntax: -w, --network OPTIONS Connect the guest to the host network. Examples for specifying the network type: bridge=BRIDGE
Connect to a bridge device in the host called BRIDGE. Use this option if the host has static networking config & the guest requires full outbound and inbound connectivity to/from the LAN. Also use this if live migra‐
tion will be used with this guest. network=NAME
Connect to a virtual network in the host called NAME. Virtual networks can be listed, created, deleted using the virsh command line tool. In an unmodified install of libvirt there is usually a virtual network with a
name of default. Use a virtual network if the host has dynamic networking (eg NetworkManager), or using wireless. The guest will be NATed to the LAN by whichever connection is active. type=direct,source=IFACE[,source.mode=MODE]
Direct connect to host interface IFACE using macvtap. user Connect to the LAN using SLIRP. Only use this if running a QEMU guest as an unprivileged user. This provides a very limited form of NAT. none Tell virt-install not to add any default network interface. If --network is omitted a single NIC will be created in the guest. If there is a bridge device in the host with a physical interface attached, that will be used for connectivity. Failing that, the virtual network called de‐
fault will be used. This option can be specified multiple times to setup more than one NIC. Some example suboptions: model.type or model
Network device model as seen by the guest. Value can be any nic model supported by the hypervisor, e.g.: 'e1000', 'rtl8139', 'virtio', ... mac.address or mac
Fixed MAC address for the guest; If this parameter is omitted, or the value RANDOM is specified a suitable address will be randomly generated. For Xen virtual machines it is required that the first 3 pairs in the MAC
address be the sequence '00:16:3e', while for QEMU or KVM virtual machines it must be '52:54:00'. filterref.filter
Controlling firewall and network filtering in libvirt. Value can be any nwfilter defined by the virsh 'nwfilter' subcommands. Available filters can be listed by running 'virsh nwfilter-list', e.g.: 'clean-traffic',
'no-mac-spoofing', ... virtualport.* options
Configure the device virtual port profile. This is used for 802.Qbg, 802.Qbh, midonet, and openvswitch config. Use --network=? to see a list of all available sub options. Complete details at https://libvirt.org/formatdomain.html#elementsNICS This option deprecates -m/--mac, -b/--bridge, and --nonetworks |
When I create a VM using virt-install, the VM gets connected to the virbr0 network interface automatically by generating this XML configuration:
<interface type="network">
<source network="default"/>
<mac address="52:54:00:6a:40:f8"/>
<model type="e1000e"/>
</interface>Now I'm trying to replicate that.
Checking the default libvirt network config at /var/lib/libvirt/dnsmasq/default.conf, I was able to tell the network interface name is virbr0.
I managed to tell qemu to use that same interface like this:
qemu-system-x86_64 -net nic -net bridge,br=virbr0" ...
But I couldn't figure out how to specify a custom MAC address like it's done in the XML config. Could someone enlighten me?
For a tap device it seems you can set the MAC address like this
-netdev type=tap,id=net0,ifname=tap0,script=tap_ifup,downscript=tap_ifdown,vhost=on \
-device virtio-net-pci,netdev=net0,addr=19.0,mac=52:54:00:6a:40:f8But that's not what I want. I just want to use that virbr0 bridge.
| How to tell qemu to use a specific MAC adderss on a network bridge? |
Solution found.
I think libvirt read completion from
/usr/share/bash-completion/completions/vshBut read from an "intruder" old file in /etc/bash_completion.d/virsh_bash_completion
I solved copy this file into /etc/bash_completion.d/virsh_bash_completion
sudo cp /usr/share/bash-completion/completions/vsh /etc/bash_completion.d/virsh_bash_completionNow works all.
|
Very strange situation on Slackware-current.
With libvirt-6.8.0 compiled by source.
Let start bash completion
virst st<TAB>
virsh start OKvirsh start --dom<TAB>
virsh start --domain OKvirsh start --domain <TAB>
Display all 235 possibilities? (y or n)235 possibilities? I have only 15 domains configured and the 235 files are my files and dirs in home, seems bash completion cannot complete the domain list, the other commands (virsh domiflist, virsh dominfo, virsh domifaddr) works fine with tab completion. All expect domain list.
I have try removing all libvirt files, and reinstall libvirt but nothing...
what can block my domain bash completion?
I have tried to debug bash
set -xRun command
virsh start --domain ce<TAB>+ local flag_all=1 array ret a b ifaces nwfilters files
+ COMPREPLY=()
+ cur=cen
+ prev=--domain
+++ virsh -h
+++ grep '^ '
+++ cut '-d ' -f5
+++ virsh -h
+++ cut -d= -f1
+++ grep '\--'
+++ cut '-d ' -f7
++ echo '-c
-d
-e
-h
-k-K-l
-q
-r
-t
-v
-Vattach-device
attach-disk
...
very long list of virsh commands
cd
echo
exit
help
pwd
quit
connect' '--connect
--debug
--escape
--help
--keepalive-interval
--keepalive-count
--log
--quiet
--readonly
--timing'
+ cmds='-c
-d
-e
-h
-k-K-l
-q
-r
-t
-v
-Vattach-device
...
very long list of virsh commands
echo
exit
help
pwd
quit
connect --connect
--debug
--escape
--help
--keepalive-interval
--keepalive-count
--log
--quiet
--readonly
--timing'
++ virsh help
++ grep '^ '
++ cut '-d ' -f5
+ cmds_help='attach-device
attach-disk
attach-interface
autostart
blkdeviotune
blkiotune
blockcommit
...very long list of virsh commands
cd
echo
exit
help
pwd
quit
connect'
+ case "$prev" in
++ _virsh_list_domains 1
++ local flag_all=1 flags
++ '[' 1 -eq 1 ']'
++ flags=--all
++ virsh -q list --all
++ cut '-d ' -f7
++ awk '{print $1}'
+ doms=
+ COMPREPLY=($(compgen -W "$doms" -- "$cur"))
++ compgen -W '' -- cen
+ return 0 | Libvirt and bash completion on Slackware-current: why domain is not completed? |
By default, sudo virsh will access the system libvirt instance.
virsh as an unprivileged user, will try to access the libvirt instance for that user.
You have a VM called server1 in the user instance, and a VM called server1 in the system instance, but these are not the same VM :). Your output shows they have different memory configurations, for example.
|
The server1's correct state is shut off but when i run the command as normal user it shows the state as running for normal user and shut off with sudo
[msingh@localhost VMFiles]$ virsh list --all
Id Name State
----------------------------------------------------
1 server1 running[msingh@localhost VMFiles]$ sudo virsh list --all
[sudo] password for msingh:
Id Name State
----------------------------------------------------
- generic shut off
- server1 shut off
- server2 shut off
- windows shut off[msingh@localhost VMFiles]$ here is another command:
[msingh@localhost server1]$ sudo virsh dominfo server1
Id: -
Name: server1
UUID: acd31081-b513-4e46-b2a2-20ad6bb9ac2e
OS Type: hvm
State: shut off
CPU(s): 1
Max memory: 1048576 KiB
Used memory: 1048576 KiB
Persistent: yes
Autostart: disable
Managed save: no
Security model: selinux
Security DOI: 0[msingh@localhost server1]$ virsh dominfo server1
Id: 1
Name: server1
UUID: 8f6fa56a-b062-424a-9100-7f411df1c28b
OS Type: hvm
State: running
CPU(s): 1
CPU time: 18.8s
Max memory: 1024 KiB
Used memory: 2048 KiB
Persistent: yes
Autostart: disable
Managed save: no
Security model: selinux
Security DOI: 0
Security label: unconfined_u:unconfined_r:svirt_t:s0:c290,c658 (enforcing) | Why does "virsh list --all" shows running as normal user but "shut off" with sudo? |
The solution is to enable networking on the qemu-instance qemu:///session, because gnome-boxes creates the virtual machines on that instance, which is by default not able to have sophisticated networking access.
Either enabling it by giving qemu-bridge-helper a setuid bit:
sudo chmod 4755 /usr/lib/qemu/qemu-bridge-helper
or you can enable all executables in that folder:
sudo chmod 4755 /usr/lib/qemu/*
More sophisticated information can be found here and here:https://www.reddit.com/r/openSUSE/comments/q9jcmy/tutorial_how_to_use_bridged_network_on_a_gnome/
https://blog.wikichoon.com/2016/01/qemusystem-vs-qemusession.html |
in short: My virtual machine named CONAN01 is not starting up in gnome-boxes, I receive/see different errors and do not know what the real issues behind them are:
Error 1:
When starting gnome-boxes from the Gnome desktop environment and clicking on my virtual machine CONAN01 to start it up, I receive a pop-up message with the option to open the error log and in this error log I can see the last lines, which state:
2022-06-15 09:39:22.707+0000: Domain id=1 is tainted: host-cpu
char device redirected to /dev/pts/0 (label charserial0)
2022-06-15T09:39:22.800582Z qemu-system-x86_64: warning: This family of AMD CPU doesn't support hyperthreading(2)
Please configure -smp options properly or try enabling topoext feature.
2022-06-15T10:30:56.757942Z qemu-system-x86_64: terminating on signal 15 from pid 3544 (/lib/systemd/systemd)Error 2:
When using the terminal to start gnome-boxes and then using the mouse to click and run my virtual machine CONAN01, I receive following error:gnome-boxeserror output at gnome-boxes startup:
(gnome-boxes:709111): Gtk-WARNING **: 22:02:27.216: GtkFlowBox with a model will ignore sort and filter functions(gnome-boxes:709111): Gtk-WARNING **: 22:02:27.217: GtkListBox with a model will ignore sort and filter functions(gnome-boxes:709111): GLib-GObject-WARNING **: 22:02:28.067: ../../../gobject/gsignal.c:2715: handler '2888' of instance '0x562fb55b44e0' is not blockederror output at virtual machine CONAN01 startup:
(gnome-boxes:709111): Boxes-WARNING **: 22:02:32.045: machine.vala:605: Failed to start CONAN01: Unable to start domain: internal error: /usr/lib/qemu/qemu-bridge-helper --use-vnet --br=virbr0 --fd=31: failed to communicate with bridge helper: Transport endpoint is not connected
stderr=failed to create tun device: Operation not permittedError 3:
When executing the gnome-boxes – CLI checks by performing the necessary command, I receive following information:gnome-boxes --checksinformation output:
(gnome-boxes:717997): Boxes-WARNING **: 22:50:30.599: util-app.vala:376: Failed to execute child process ?restorecon? (No such file or directory)
• The CPU is capable of virtualization: yes
• The KVM module is loaded: yes
• Libvirt KVM guest available: yes
• Boxes storage pool available: no
/root/.local/share/gnome-boxes/images is known to libvirt as GNOME Boxes’s storage pool but this directory does not exist
• The SELinux context is default: noReport bugs to <http://gitlab.gnome.org/gnome/gnome-boxes/issues>.
Boxes home page: <https://wiki.gnome.org/Apps/Boxes>.Despite changing the location of the storage pool by using the necessary commands, but the output showing the XML – configuration has not changed, virsh and gnome-boxes still think the old location is valid, my intend was to change “/home/myusername/.local/share/gnome-boxes/images”:virsh pool-info gnome-boxesName: gnome-boxes
UUID: edb0bf37-df0f-4295-a3cf-0ced96970de0
State: running
Persistent: yes
Autostart: yes
Capacity: 907,44 GiB
Allocation: 531,49 GiB
Available: 375,95 GiBvirsh pool-dumpxml gnome-boxes<pool type='dir'>
<name>gnome-boxes</name>
<uuid>edb0bf37-df0f-4295-a3cf-0ced96970de0</uuid>
<capacity unit='bytes'>974357393408</capacity>
<allocation unit='bytes'>570679726080</allocation>
<available unit='bytes'>403677667328</available>
<source>
</source>
<target>
<path>/root/.local/share/gnome-boxes/images</path>
<permissions>
<mode>0744</mode>
<owner>0</owner>
<group>0</group>
</permissions>
</target>
</pool>sudo virsh pool-edit gnome-boxesvirsh pool-dumpxml gnome-boxes<pool type='dir'>
<name>gnome-boxes</name>
<uuid>edb0bf37-df0f-4295-a3cf-0ced96970de0</uuid>
<capacity unit='bytes'>974357393408</capacity>
<allocation unit='bytes'>570679726080</allocation>
<available unit='bytes'>403677667328</available>
<source>
</source>
<target>
<path>/root/.local/share/gnome-boxes/images</path>
<permissions>
<mode>0744</mode>
<owner>0</owner>
<group>0</group>
</permissions>
</target>
</pool> | How to fix (several) VM start-up issues in gnome-boxes? |
For anyone curious, I did not find a solution to the issue. However, I managed to avoid the issue by hosting a samba share on the host (using the dperson/samba docker container) and then on the guest, I installed cifs-utils and then added this line to \etc\fstab:
//192.168.1.7/Shared /media/shared cifs guest,uid=1000,iocharset=utf8,vers=3.0 0 0Where 192.168.1.7 is the IP address of the host, Shared is the name of the Samba share, and /media/shared is where I mounted the share in the guest.
|
I have created a Ubuntu VM on a server running Ubuntu Server 16.04.5 LTS using the following command:
sudo virt-install \
--name TEST \
--memory 2048 \
--vcpus 2 \
--location 'http://archive.ubuntu.com/ubuntu/dists/xenial/main/installer-amd64/' \
--os-variant ubuntu16.04 \
--disk path=/pools/pool0/images/vm/test,size=150,bus=virtio,sparse=no,format=qcow2 \
--filesystem type=mount,source=/pools/pool0/volumes/shared,target=shared,mode=mapped \
--network network=vms \
--graphics none \
--virt-type kvm \
--hvm \
--console pty,target_type=serial \
--extra-args 'console=ttyS0,115200n8 serial'Note that I have created a shared folder, called shared with mapped access in order to allow reading and writing on the guest.
I then start the VM with this command:
virsh start TEST --consoleInside the guest, I have edited /etc/fstab to auto-mount the shared folder with this line, where UID 1000 is my user and GID 1000 is the associated group which contains no other members:
shared /mnt 9p trans=virtio,version=9p2000.L,rw,uid=1000,gid=1000 0 0In the /mnt directory on the guest, running ls -ln gives the following output:
$ ls -ln /mnt
total 42
drwxrwxr-x 8 1000 1000 8 Jul 28 23:52 Backups
drwxrwxr-x 6 1000 1000 6 Dec 28 00:15 Media
drwxrwxr-x 6 1000 1000 67 Mar 31 2018 Misc
drwxrwxr-x 2 1000 1000 4 Mar 31 2018 RecipesI get the same output when running ls -ln on the host in the /pools/pool0/volumes/shared directory:
$ ls -ln /pools/pool0/volumes/shared
total 42
drwxrwxr-x 8 1000 1000 8 Jul 28 23:52 Backups
drwxrwxr-x 6 1000 1000 6 Dec 28 00:15 Media
drwxrwxr-x 6 1000 1000 67 Mar 31 2018 Misc
drwxrwxr-x 2 1000 1000 4 Mar 31 2018 RecipesIn the guest, I can create and modify files and folders as myself, an unprivileged user:
$ mkdir /mnt/Media/test-dir
$ touch /mnt/Media/test-file
$ ls -ln /mnt/Media
total 75
drwxrwxr-x 199 1000 1000 199 Dec 28 22:07 Movies
drwxrwxr-x 152 1000 1000 153 Dec 25 16:26 Music
drwxrwxr-x 75 1000 1000 75 Jul 16 21:02 Photos
drwxrwxr-x 2 1000 1000 2 Dec 29 20:30 test-dir
-rw-rw-r-- 1 1000 1000 0 Dec 29 20:31 test-file
drwxrwxr-x 15 1000 1000 15 Dec 18 15:40 TV ShowsHowever, on the host OS, these files and folders have been given root only access:
$ ls -ln /pools/pool0/volumes/shared/Media
total 75
drwxrwxr-x 199 1000 1000 199 Dec 28 22:07 Movies
drwxrwxr-x 152 1000 1000 153 Dec 25 16:26 Music
drwxrwxr-x 75 1000 1000 75 Jul 16 21:02 Photos
drwx------ 2 0 0 2 Dec 29 20:30 test-dir
-rw------- 1 0 0 0 Dec 29 20:31 test-file
drwxrwxr-x 15 1000 1000 15 Dec 18 15:40 TV ShowsI run automated scripts on my server, and for these to work I need these folders and directories to be created with UID 1000, GID 1000, permissions of rwxrwxr-x (775) for directories, and permissions of rw-rw-r-- (664) for files. I do not want to have to manually run chmod and chown with sudo each time I create a new file / directory.
I need to fix this issue, preferably without having to re-install the VM from scratch.
| Libvirt Ubuntu VM: files created on guest in shared folder given root-only access on host |
The question was solved, after reading this blog post.
I will write the solution in short form:boot from a live cd with
use gdisk (if you use GPT) otherwise you could go with good old fdisk
note your partition settings, in my case gdisk -l /dev/sdb
delete your partition with
create a new partition with the exact same alignment as the previous one (in my example starting at block 2048)
write your new partition table
run partprobe -s to refresh the partition table without a reboot
resize your physical volume with pvresize /dev/sdb1 or wherever your pv is (use pvs to determine if you don't know)
now resize your logical volume with lvextend -l +100%FREE /dev/file/of/your/lv, in my case sudo lvextend -l +100%FREE /dev/linuxvg/home
resize the filesystem sudo resize2fs /dev/linuxvg/home
first check the consistency sudo e2fsck -f /dev/linuxvg/home
enjoy :) |
On my 240 GB SSD I had at first two partitions, one containing the Logical Volume with Linux Mint and the other had contained a NTFS partition to share with Windows.
Now I removed the NTFS partition and want to extend my logical volume group to use the released disk space.
How do I extend the volume group, my logical volume containing /home and the filesystem (ext4) on /home? Is this possible to do online?
PS: Yes, I know that I have to backup my data :)
/dev/sdb/ (240GB)
linuxvg (160GB) should use 100% of the disk space
swap
root
home (ext4, 128GB) should be extended to use the remaining spaceoutput of sudo vgdisplay:
--- Volume group ---
VG Name linuxvg
System ID
Format lvm2
Metadata Areas 1
Metadata Sequence No 4
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 3
Open LV 3
Max PV 0
Cur PV 1
Act PV 1
VG Size 160,00 GiB
PE Size 4,00 MiB
Total PE 40959
Alloc PE / Size 40959 / 160,00 GiB
Free PE / Size 0 / 0
VG UUID ...
--- Logical volume ---
LV Path /dev/linuxvg/swap
LV Name swap
VG Name linuxvg
LV UUID ...
LV Write Access read/write
LV Creation host, time mint, 2013-08-06 22:48:32 +0200
LV Status available
# open 2
LV Size 8,00 GiB
Current LE 2048
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 252:0
--- Logical volume ---
LV Path /dev/linuxvg/root
LV Name root
VG Name linuxvg
LV UUID ...
LV Write Access read/write
LV Creation host, time mint, 2013-08-06 22:48:43 +0200
LV Status available
# open 1
LV Size 24,00 GiB
Current LE 6144
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 252:1
--- Logical volume ---
LV Path /dev/linuxvg/home
LV Name home
VG Name linuxvg
LV UUID ...
LV Write Access read/write
LV Creation host, time mint, 2013-08-06 22:48:57 +0200
LV Status available
# open 1
LV Size 128,00 GiB
Current LE 32767
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 252:2
--- Physical volumes ---
PV Name /dev/sdb1
PV UUID ...
PV Status allocatable
Total PE / Free PE 40959 / 0output of sudo fdisk -l:
Disk /dev/sdb: 240.1 GB, 240057409536 bytes
255 heads, 63 sectors/track, 29185 cylinders, total 468862128 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000 Device Boot Start End Blocks Id System
/dev/sdb1 1 468862127 234431063+ ee GPTDisk /dev/mapper/linuxvg-swap: 8589 MB, 8589934592 bytes
255 heads, 63 sectors/track, 1044 cylinders, total 16777216 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000Disk /dev/mapper/linuxvg-root: 25.8 GB, 25769803776 bytes
255 heads, 63 sectors/track, 3133 cylinders, total 50331648 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000Disk /dev/mapper/linuxvg-home: 137.4 GB, 137434759168 bytes
255 heads, 63 sectors/track, 16708 cylinders, total 268427264 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000 | How do I extend a partition with a LVM and the contained physical volume and logical volume? |
The problem lies in a PulseAudio module called module-role-cork which exists to pause music and video during phone calls. All applications are given a media-role property which can be either music video or phone. The Cork module will give any application tagged phone exclusive access to the PulseAudio server and pause anything not tagged as such.
Simply comment out the line with load-module module-role-cork from the file /etc/pulse/default.pa
Note: Credit to David Hyrule, from this blog.
|
I use ArchLinux, and I recently installed Spotify which is working fine, except for one thing:
Every time any program triggers a system sound, the player volume is automatically muted in the mixer. How can I stop this?
I have verified that this also is happening with vlc, so I'm guessing is something related to Gnome.
Could it something related to pulseaudio?
| How to stop gnome from muting my music? |
A one-liner to parse amixer's output for volume in a status bar:
awk -F"[][]" '/dB/ { print $2 }' <(amixer sget Master)
Edit:
As of November 2020, the updated amixer for Arch Linux is 1.2.4 which has no 'dB' in the output. So, the command should replaced by:
awk -F"[][]" '/Left:/ { print $2 }' <(amixer sget Master)
|
I have a text status bar on a tiling window manager and I am using tcl to feed information to it. At the moment I need a command line that output the volume level 0% to 100%. I am using Arch Linux.
| How to get volume level from the command line? |
You should find that get volume settings will return an object containing among other things the output volume and the alert volume. So for example you could do this to retrieve the entire object:
osascript -e 'get volume settings'or rather maybe this to grab just the output volume (e.g. rather than the alert volume):
osascript -e 'set ovol to output volume of (get volume settings)'... but note that not all audio devices will have direct software control over volume settings. For example your display audio should have control; however, a firewire or USB i/o board probably would not have those settings under software control (since they might be physical knobs). If the particular setting is not under the control of software then it will show up in the object returned from get volume settings as "missing value" or something like that.
|
I would like to check the current volume level from the CLI on my Mac. I know I can set it like this:
osascript -e 'set volume <N>'But that doesn't seem to work when trying to get the current volume level.
$ osascript -e 'get volume'
4:10: execution error: The variable volume is not defined. (-2753) | Get the current volume level in OS X Terminal CLI? |
It's about online resize.
For example if you use LVM, create a LV of 1G size, and put LUKS on that, it's like this:
# lvcreate -L1G -n test VG
# cryptsetup luksFormat /dev/mapper/VG-test
# cryptsetup luksOpen /dev/mapper/VG-test lukstest
# blockdev --getsize64 /dev/mapper/VG-test
1073741824
# blockdev --getsize64 /dev/mapper/lukstest
1071644672So the LUKS device is about the same size as the VG-test device (1G minus 2MiB used by the LUKS header).
Now what happens when you make the LV larger?
# lvresize -L+1G /dev/mapper/VG-test
Size of logical volume VG/test changed from 1.00 GiB (16 extents) to 2.00 GiB (32 extents).
Logical volume test successfully resized.
# blockdev --getsize64 /dev/mapper/VG-test
2147483648
# blockdev --getsize64 /dev/mapper/lukstest
1071644672The LV is 2G large now, but the LUKS device is still stuck at 1G, as that was the size it was originally opened with.
Once you luksClose and luksOpen, it would also be 2G — because LUKS does not store a size, it defaults to the device size at the time you open it. So close and open (or simply rebooting) would update the crypt mapping to the new device size. However, since you can only close a container after umounting/stopping everything inside of it, this is basically an offline resize.
But maybe you have a mounted filesystem on the LUKS, it's in use, and you don't want to umount it for the resize, and that's where cryptsetup resize comes in as an online resize operation.
# cryptsetup resize /dev/mapper/lukstest
# blockdev --getsize64 /dev/mapper/lukstest
2145386496cryptsetup resize updates the active crypt mapping to the new device size, no umount required, and then you can follow it up with resize2fs or whatever to also grow the mounted filesystem itself online.
If you don't mind rebooting or remounting, you'll never need cryptsetup resize as it happens automatically offline. But if you want to do it online, that's the only way.When shrinking (cryptsetup resize --size x), the resize is temporary. LUKS does not store device size, so next time you luksOpen, it will simply use the device size again. So shrinking sticks only if the backing device was also shrunk accordingly.
For a successful shrink you have to work backwards... growing is grow partition first, then LUKS, then filesystem... shrinking is shrink filesystem first, and partition last.If the resize doesn't work, it's most likely due to the backing device not being resized, for example the kernel may refuse changes to the partition table while the drive is in use. Check with blockdev that all device layers have the sizes you expect them to have.
|
The LUKS / dm-crypt / cryptsetup FAQ page says:2.15 Can I resize a dm-crypt or LUKS partition?
Yes, you can, as neither dm-crypt nor LUKS stores partition size.I'm befuzzled:What is "resized" if no size information is stored?
How does a "resize" get remembered across open / closes of a encrypted volume? | What does `cryptsetup resize` do if LUKS doesn't store partition size? |
As said by @ilkkachu, if you take a look at the mount(8) manpage, all your doubts should go away. Quoting the manpages:
-w, --rw, --read-write
Mount the filesystem read/write. This is the default. A synonym is -o rw.Means: Not needed at all, since rw is the default, and it is part of the defaults option
nofail Do not report errors for this device if it does not exist.Means: If the device is not enable after you boot and mount it using fstab, no errors will be reported. You will need to know if a disk can be ignored if not mounted. Pretty useful on usb drivers, but i see no point on using this on a server...
noatime
Do not update inode access times on this filesystem (e.g., for faster access on the
news spool to speed up news servers).Means: No read operation is a "pure" read operation on filesystems. Even if you only cat file for example, a little write operation will update the last time the inode of this file was accessed. It's pretty useful on some situations(like caching servers), but it can be dangerous if used on sync technologies like Dropbox. I'm no one to judge here what is best for you, if noatime set or ignored...
discard/nodiscard
Controls whether ext4 should issue discard/TRIM commands to the underlying block device
when blocks are freed.This is useful for SSD devices and sparse/thinly
-provisioned LUNs, but it is off by default until sufficient testing has been done.Means: TRIM feature from ssds. Take your time to read on this guy, and probe if your ssd support this feature(pretty much all modern ssds suport it). hdparm -I /dev/sdx | grep "TRIM supported" will tell you if trim is supported on your ssd.
As for today, you could achieve better performance and data health by Periodic trimming instead of a continuous trimming on your fstab. There is even a in-kernel device blacklist for continuous trimming since it can cause data corruption due to non-queued operations.
defaults
Use default options: rw, suid, dev, exec, auto, nouser, and async.tl;dr: on your question, rw can be removed(defaults already imply rw), nofail is up to you, noatime is up to you, the same way discard is just up to your hardware features.
|
I am using OpenStack Cloud and using LVM on RHEL 7 to manage volumes. As per my use case, I should be able to detach and attach these volumes to different instances.
While updating fstab, I have used defaults,nofail for now but I am not sure what exactly I should be using. I am aware of these options:
rw, nofail, noatime, discard, defaults But I don't how to use them. What should be the ideal configuration for my use case ?
| When and where to use rw,nofail,noatime,discard,defaults? |
Since the filesystem you'll need the disk removed from is your root filesystem, and the filesystem type is ext4, you'll have to boot the system from some live Linux boot media first. Ubuntu Live would probably work just fine for this.
Once booted from the external media, run sudo vgchange -ay ubuntu-vg to activate the volume group so that you'll be able to access the LVs, but don't mount the filesystem: ext2/3/4 filesystems need to be unmounted for shrinking. Then shrink the filesystem to 10G (or whatever size you wish - it can easily be extended again later, even on-line):
sudo resize2fs /dev/mapper/ubuntu--vg-ubuntu--lv 10GPay attention to the messages output by resize2fs - if it says the filesystem cannot be shrunk that far, specify a bigger size and try again.
This is the only step that needs to be done while booted on the external media; for everything after this point, you can boot the system normally.
At this point, the filesystem should have been shrunk to 10G (or whatever size you specified). The next step is to shrink the LV. It is vitally important that the new size of the LV should be exactly the same or greater than the new size of the filesystem! You don't want to cut off the tail end of the filesystem when shrinking the LV. It's safest to specify a slightly bigger size here:
sudo lvreduce -L 15G /dev/mapper/ubuntu--vg-ubuntu--lvNow, use pvdisplay or pvs to see if LVM now considers /dev/sdb1 totally free or not. In pvdisplay, the Total PE and Free PE values for sdb1 should be equal - in pvs output, the PFree value should equal PSize respectively. If this is not the case, then it will be time to use pvmove:
sudo pvmove /dev/sdb1After this, the sdb1 PV should definitely be totally free according to LVM and it can be reduced out of the VG.
sudo vgreduce vg-ubuntu /dev/sdb1If you wish, you can then remove the LVM signature from the ex-PV:
sudo pvremove /dev/sdb1But if you are going to overwrite it anyway, you can omit this step.
After these steps, the shrunken filesystem will still be sized at 10G (or whatever you specified) even though the LV might be somewhat bigger than that. To fix that:
sudo resize2fs /dev/mapper/ubuntu--vg-ubuntu--lvWhen extending a filesystem, you don't have to specify a size: the tool will automatically extend the filesystem to match the exact size of the innermost device containing it. In this case, the filesystem will be sized according to the size of the LV.
Later, if you wish to extend the LV+filesystem, you can do it with just two commands:
sudo lvextend -L <new size> /dev/mapper/ubuntu--vg-ubuntu--lv
sudo resize2fs /dev/mapper/ubuntu--vg-ubuntu--lvYou can do this even while the filesystem is in use and mounted. Because shrinking a filesystem is harder than extending it, it might be useful to hold some amount of unallocated space in reserve at the LVM level - you will be able to use it at a moment's notice to create new LVs and/or to extend existing LVs in the same VG as needed.
|
Can anyone help ? I have 2 disks spanning my main partitions. 1 is 460Gb and the other is a 1TB. I would like to remove the 1TB - I would like to use it in another machine.
The volume group isn't using a lot of space anyway, I only have docker with a few containers using that disk and my docker container volumes are on a different physical disk anyway.
If I just remove the disk ([physically]), it is going to cause problems right?
Here is some infopvdisplay --- Physical volume ---
PV Name /dev/sda3
VG Name ubuntu-vg
PV Size <464.26 GiB / not usable 2.00 MiB
Allocatable yes (but full)
PE Size 4.00 MiB
Total PE 118850
Free PE 0
Allocated PE 118850
PV UUID DA7Q8E-zJEz-2FzO-N64t-HtU3-2Z8P-UQydU4 --- Physical volume ---
PV Name /dev/sdb1
VG Name ubuntu-vg
PV Size 931.51 GiB / not usable 4.69 MiB
Allocatable yes (but full)
PE Size 4.00 MiB
Total PE 238466
Free PE 0
Allocated PE 238466
PV UUID Sp6b1v-nOj2-XXdb-GZYf-1Vej-cfdr-qLB3GULVM confuses me a little :-)
Is there not just a simple case of saying,
"remove yourself from the VG and assing anything you are using the remaining group member" ?
Its worth noting that the 1TB was added afterwards, so assume its easier to remove ?
Any help really appreciated
EDIT
Also some more info
df -h
Filesystem Size Used Avail Use% Mounted on
udev 16G 0 16G 0% /dev
tmpfs 3.2G 1.4M 3.2G 1% /run
/dev/mapper/ubuntu--vg-ubuntu--lv 1.4T 5.1G 1.3T 1% /It sames its using only 1%
also output of lvs
lvs
LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
ubuntu-lv ubuntu-vg -wi-ao---- 1.36tEDIT
pvdisplay -m
--- Physical volume ---
PV Name /dev/sda3
VG Name ubuntu-vg
PV Size <464.26 GiB / not usable 2.00 MiB
Allocatable yes (but full)
PE Size 4.00 MiB
Total PE 118850
Free PE 0
Allocated PE 118850
PV UUID DA7Q8E-zJEz-2FzO-N64t-HtU3-2Z8P-UQydU4 --- Physical Segments ---
Physical extent 0 to 118849:
Logical volume /dev/ubuntu-vg/ubuntu-lv
Logical extents 0 to 118849 --- Physical volume ---
PV Name /dev/sdb1
VG Name ubuntu-vg
PV Size 931.51 GiB / not usable 4.69 MiB
Allocatable NO
PE Size 4.00 MiB
Total PE 238466
Free PE 0
Allocated PE 238466
PV UUID Sp6b1v-nOj2-XXdb-GZYf-1Vej-cfdr-qLB3GU --- Physical Segments ---
Physical extent 0 to 238465:
Logical volume /dev/ubuntu-vg/ubuntu-lv
Logical extents 118850 to 357315EDIT
Output of
lsblk -f
NAME FSTYPE LABEL UUID MOUNTPOINT
loop0 squashfs /snap/core/9066
loop2 squashfs /snap/core/9289
sda
├─sda1 vfat E6CC-2695 /boot/efi
├─sda2 ext4 0909ad53-d6a7-48c7-b998-ac36c8f629b7 /boot
└─sda3 LVM2_membe DA7Q8E-zJEz-2FzO-N64t-HtU3-2Z8P-UQydU4
└─ubuntu--vg-ubuntu--lv
ext4 b64f2bf4-cd6c-4c21-9009-76faa2627a6b /
sdb
└─sdb1 LVM2_membe Sp6b1v-nOj2-XXdb-GZYf-1Vej-cfdr-qLB3GU
└─ubuntu--vg-ubuntu--lv
ext4 b64f2bf4-cd6c-4c21-9009-76faa2627a6b /
sdc xfs 1a9d0e4e-5cec-49f3-9634-37021f65da38 /gluster/bricks/2sdc above is a different drive - and not related.
| How to remove a disk from an lvm partition? |
You don't want to mix different sector sizes in a single VG. Newer versions of LVM don't even allow creating VG on PVs with mixed sector sizes by default (older versions show only the warning message you saw). The problem is not with the VG, but with the LVs and filesystems -- if you resize or move LV to the larger sector size PV the filesystem can get corrupted.
You can create the VG, but you need to make sure your LVs are allocated only on PVs with same sector size and remember to keep this setup in the future (you can specify which PV will be used with lvcreate), but I recommend creating two separate VGs. If one of your disks is 512 sectors NVMe you might be also able to switch it to 4096 sectors using nvme-cli (or vice versa to make both disks same sector size).
Few related linksLVM Bugzilla: FS fails to mount if we lvextend the LV with a new PV with different sector size
LVM ML: Filesystem corruption with LVM's pvmove onto a PV with a larger physical block size
Commit changing the default behaviour |
I have two hard drives of different physical sector size. I would like to create an LVM volume group with them, however, when I do so with vgcreate, I get a warning telling me that the two disks have different physical sector size. Is there something to be concerned about?
| Is there any risk to create an LVM group with two disks of different physical sector size? |
An extra 80 GB in EC2 EBS costs something under $12 per month. On-line manipulations are likely to take more than one hour of your work, and a risk of downtime if something goes wrong - how much is that worth for you?
Pay for some extra capacity, add it to your instance as a third disk xvdc, initialize it as a LVM PV (you don't even have to put a partition table on it: just pvcreate /dev/xvdc will be sufficient). Then add the new PV to your rootrhel VG (vgextend rootrhel /dev/xvdc) and now you can extend your /storetmp with the added capacity.
lvextend -L +80G /dev/mapper/rootrhel-storetmp
xfs_growfs /storetmp #or the appropriate tool for your filesystem type With your immediate problem solved, you can now schedule for some downtime at suitable time.
If you are using XFS filesystem (as RHEL/CentOS 7 does by default), then during the next scheduled downtime, you'll create tarballs of the current contents of /store and /transient, unmount and remove the entire storerhel VG, add its PV xvdb3 to the rootrhel VG and then recreate the LVs for /store and /transient filesystems using more realistic estimates for their capacity needs, and restore the contents of the tarballs. End of downtime.
Now your rootrhel VG has three PVs: xvdb2, xvdb3 and xvdc, and plenty of space for your needs.
If you want to stop paying for xvdc, you can use pvmove /dev/xvdc to automatically migrate the data within the VG off the xvdc and onto unallocated space within xvdb2 and/or xvdb3. You can do this on-line; just don't do it at the time of your peak I/O workload to avoid taking a performance hit. Then vgreduce rootrhel /dev/xvdc, echo 1 > /sys/block/xvdc/device/delete to tell the kernel that the xvdc device is going away, and then tell Amazon that you don't need your xvdc disk any more.
I have nearly 20 years of experience working with LVM disk storage (first with HP-UX LVM, and later with Linux LVM once it matured enough to be usable in enterprise environment). These are the rules of thumb I've come to use with LVM:You should never create two VGs when one is enough. In particular, having two VGs on a single disk is most likely a mistake that will cause you headache. Reallocating disk capacity within a VG is as flexible as your filesystem type allows; moving capacity between VGs in chunks smaller than one already-existing PV is usually not worth the hassle.If there is uncertainty in your disk space requirements (and there always is), keep your LVs on the small side and some unallocated space in reserve. As long as your VG has unallocated capacity available, you can extend LVs and filesystems in them on-line as needed with one or two quick commands. It's a one-banana job for a trained monkey junior sysadmin.
If there is no unallocated capacity in the VG, get a new disk, initialize it as a new PV, add it to the VG that needs capacity, and then go on with the extension as usual. Shrinking filesystems is more error-prone, may require downtime or may even be impossible without backing up & recreating the filesystem in smaller size, depending on filesystem type. So you'll want to avoid situations that require on-line shrinking of filesystems as much as possible.Micro-management of disk space can be risky, and is a lot of work. Work is expensive. Okay. Technically you could create a 80 GB file on /store, losetup it into a loop device, then make that into a PV you could add into your rootrhel VG... but doing that would result in a system that would most likely drop into a single user recovery mode at boot unless you set up a customized start-up script for these filesystems and VGs and got it right at the first time.
Get it wrong, and the next time your system is rebooted for any reason you'll have to take some unplanned downtime for troubleshooting and fixing, or more realistically recreating the filesystems from scratch and restoring the contents from backups because it's simpler than trying to troubleshoot this jury-rigged mess.
Or if you are using ext4 filesystem that can be on-line reduced, you could shrink the /store filesystem, shrink the LV, use pvmove --alloc anywhere to consolidate the free space to the tail end of the xvdb3 PV, shrink the PV, shrink the partition, run partprobe to make the changes effective without a reboot, then create a new partition xvdb4, initialize it as a new PV and add it to rootrhel VG...
BUT if you make one mistake in this sequence so that your filesystem/PV extends beyond its LV/partition container, and your filesystem gets switched into read-only mode with an error flag that can be only reset by running a filesystem check, resulting in mandatory unplanned downtime.
|
I am setting up a redhat ec2 instance and by default the software I am using (called qradar) created the following volumes on the two 500g ebs storage devices attached to the instance:
$ lvs
LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
storetmp rootrhel -wi-ao---- 20.00g
varlog rootrhel -wi-ao---- <20.00g
store storerhel -wi-ao---- <348.80g
transient storerhel -wi-ao---- <87.20g $ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/xvda2 500G 1.4G 499G 1% /
devtmpfs 16G 0 16G 0% /dev
tmpfs 16G 0 16G 0% /dev/shm
tmpfs 16G 17M 16G 1% /run
tmpfs 16G 0 16G 0% /sys/fs/cgroup
/dev/mapper/storerhel-store 349G 33M 349G 1% /store
/dev/mapper/storerhel-transient 88G 33M 88G 1% /transient
/dev/mapper/rootrhel-storetmp 20G 33M 20G 1% /storetmp
/dev/mapper/rootrhel-varlog 20G 35M 20G 1% /var/log
tmpfs 3.2G 0 3.2G 0% /run/user/1000I need my storetmp to be 100g. How can I move 80g of storage from store to storetmp?
It also seems that I may need to shift some space from xvdb3 to xvdb2:
# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
xvda 202:0 0 500G 0 disk
├─xvda1 202:1 0 1M 0 part
└─xvda2 202:2 0 500G 0 part /
xvdb 202:16 0 500G 0 disk
├─xvdb1 202:17 0 24G 0 part [SWAP]
├─xvdb2 202:18 0 40G 0 part
│ ├─rootrhel-varlog 253:2 0 20G 0 lvm /var/log
│ └─rootrhel-storetmp 253:3 0 20G 0 lvm /storetmp
└─xvdb3 202:19 0 436G 0 part
├─storerhel-store 253:0 0 348.8G 0 lvm /store
└─storerhel-transient 253:1 0 87.2G 0 lvm /transientNote that the directories are currently being used by the software running on the box and are not empty, so deleting them is out of the question, I need this to be done on-the-fly:
$ ls -l /dev/mapper/storerhel-transient
lrwxrwxrwx 1 root root 7 Aug 10 16:00 /dev/mapper/storerhel-transient -> ../dm-3
$ ls -l /dev/mapper/rootrhel-varlog
lrwxrwxrwx 1 root root 7 Aug 10 16:00 /dev/mapper/rootrhel-varlog -> ../dm-0
$ ls -l /dev/mapper/storerhel-store
lrwxrwxrwx 1 root root 7 Aug 17 04:10 /dev/mapper/storerhel-store -> ../dm-2 | Volume Management: How to move space from one partition to another? |
You can use pactl to change the volume. Eg, to increase:
pactl set-sink-volume 0 +10%And to decrease:
pactl set-sink-volume -- 0 -10%You need the -- here to make pactl interpret the -10% as a postitional argument. The first number is the sink to use, this may not be 0 on your system. To list the possibilities:
pactl list short sinks |
Using mate and linux mint, I would like to create another keyboard shortcut to increase and decrease the volume.
Currently, I'm using custom keyboard bindings with mate-keybinding-properties.
I bought a wireless headset which includes buttons to change the volume. Those buttons works well if I reconfigure the keybindings, but I don't want to remove the ones with keyboard.
That's why I would like to create another shortcut, but I can't find a command to do this in mate, or which one is used with the default settings.
I already found topics about amixer, but I'm not happy with it because it doesn't show the volume tooltip, and it resets the balance of my speakers when I try to increase it to more than 100%.
| Change volume with terminal |
You are running Pulseaudio, which uses ALSA to drive soundcards, but which connects to Bluetooth speakers without involving ALSA. When you set ALSA volumes with amixer, Pulseaudio notices and corrects the source/sink volumes (actually using a somewhat complicated algorithm, because ALSA volumes can be chanined), but not matter what you try, you won't be able to control Bluetooth speakers that way.
So just set the Pulseaudio volume directly. The command to do that is
pactl set-sink-volume name_of_bluetooth_speaker +3%etc. You can see the names of all your sinks with
pacmd list-sinks | grep name:Use the name without the angular brackets. There is no "master" volume.
You can also use scripts like this one which detects active sinks, and changes the volume on them.
|
I currently use custom created keyboard shortcuts to change the volume of my computer. The terminal commands I use are:
amixer sset Master 3%+
amixer sset Master 3%-This changes the volume of the "Built-in Audio Analog Stero" levels in the picture below. However, this does not control the volume of my bluetooth devices that I connect using the blueman app. In pavucontrol > Output Devices I see that the bluetooth device uses the Speaker port, but this does not work:
amixer sset Speaker 3%+
amixer: Invalid command!If this matters, MATE volume control shows:How can I have the master volume be a "global" volume able to change the volume for the bluetooth device?
More info from alsamixer:
Simple mixer control 'Master',0
Capabilities: pvolume pvolume-joined pswitch pswitch-joined
Playback channels: Mono
Limits: Playback 0 - 87
Mono: Playback 69 [79%] [-13.50dB] [on]
Simple mixer control 'Headphone',0
Capabilities: pvolume pswitch
Playback channels: Front Left - Front Right
Limits: Playback 0 - 87
Mono:
Front Left: Playback 87 [100%] [0.00dB] [on]
Front Right: Playback 87 [100%] [0.00dB] [on]
Simple mixer control 'Speaker',0
Capabilities: pswitch
Playback channels: Front Left - Front Right
Mono:
Front Left: Playback [on]
Front Right: Playback [on]
Simple mixer control 'PCM',0
Capabilities: pvolume pswitch
Playback channels: Front Left - Front Right
Limits: Playback 0 - 87
Mono:
Front Left: Playback 87 [100%] [0.00dB] [on]
Front Right: Playback 87 [100%] [0.00dB] [on]
Simple mixer control 'Beep',0
Capabilities: pvolume pswitch
Playback channels: Front Left - Front Right
Limits: Playback 0 - 31
Mono:
Front Left: Playback 0 [0%] [-34.50dB] [off]
Front Right: Playback 0 [0%] [-34.50dB] [off]
Simple mixer control 'Capture',0
Capabilities: cvolume cswitch
Capture channels: Front Left - Front Right
Limits: Capture 0 - 63
Front Left: Capture 51 [81%] [21.00dB] [off]
Front Right: Capture 51 [81%] [21.00dB] [off]
Simple mixer control 'Auto-Mute Mode',0
Capabilities: enum
Items: 'Disabled' 'Speaker Only' 'Line Out+Speaker'
Item0: 'Line Out+Speaker'
Simple mixer control 'Digital',0
Capabilities: cvolume
Capture channels: Front Left - Front Right
Limits: Capture 0 - 120
Front Left: Capture 81 [68%] [10.50dB]
Front Right: Capture 81 [68%] [10.50dB]
Simple mixer control 'Dock Mic',0
Capabilities: pvolume pswitch cswitch cswitch-joined cswitch-exclusive
Capture exclusive group: 0
Playback channels: Front Left - Front Right
Capture channels: Mono
Limits: Playback 0 - 31
Mono: Capture [off]
Front Left: Playback 0 [0%] [-34.50dB] [off]
Front Right: Playback 0 [0%] [-34.50dB] [off]
Simple mixer control 'Dock Mic Boost',0
Capabilities: volume
Playback channels: Front Left - Front Right
Capture channels: Front Left - Front Right
Limits: 0 - 3
Front Left: 0 [0%] [0.00dB]
Front Right: 0 [0%] [0.00dB]
Simple mixer control 'Headset Mic',0
Capabilities: pvolume pswitch cswitch cswitch-joined cswitch-exclusive
Capture exclusive group: 0
Playback channels: Front Left - Front Right
Capture channels: Mono
Limits: Playback 0 - 31
Mono: Capture [off]
Front Left: Playback 0 [0%] [-34.50dB] [off]
Front Right: Playback 0 [0%] [-34.50dB] [off]
Simple mixer control 'Headset Mic Boost',0
Capabilities: volume
Playback channels: Front Left - Front Right
Capture channels: Front Left - Front Right
Limits: 0 - 3
Front Left: 3 [100%] [30.00dB]
Front Right: 3 [100%] [30.00dB]
Simple mixer control 'Internal Mic',0
Capabilities: cswitch cswitch-joined cswitch-exclusive
Capture exclusive group: 0
Capture channels: Mono
Mono: Capture [on]
Simple mixer control 'Internal Mic Boost',0
Capabilities: volume
Playback channels: Front Left - Front Right
Capture channels: Front Left - Front Right
Limits: 0 - 3
Front Left: 3 [100%] [36.00dB]
Front Right: 3 [100%] [36.00dB] | Change volume on bluetooth speaker with amixer |
Answering in case someone is looking for this (or the future me):
lvconvert --type cache --cachepool cache-pool vg/lvSo in this case:
lvconvert --type cache --cachepool homeCache vg1/homeYou can see all the LVs, including the caches, with:
lvs -a |
In order to expand a Logical Volume, I had to split the cache off from it:
root@server:/home# lvextend -L+50G /dev/vg1/home
Unable to resize logical volumes of cache type.
root@server:/home# lvs
LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
home vg1 Cwi-aoC--- 250.00g [homeCache] [home_corig] 100.00 9.29 0.00
newvar vg1 Cwi-aoC--- 200.00g [Cvar_cache] [newvar_corig] 100.00 0.92 0.00
root_lv vg1 -wi-ao---- 93.07g
var vg1 -wi-ao---- 120.00g
root@server:/home# lvconvert --splitcache /dev/vg1/home
Logical volume vg1/home is not cached and cache pool vg1/homeCache is unused.
root@server:/home# lvextend -L+50G /dev/vg1/home
Size of logical volume vg1/home changed from 250.00 GiB (64000 extents) to 300.00 GiB (76800 extents).
Logical volume home successfully resized.
root@server:/home# resize2fs !$
resize2fs /dev/vg1/home
resize2fs 1.42.13 (17-May-2015)How do I re-attach the split cache back to the LV? Should I have used --uncache instead to destroy the cache and then rebuild it? If so, what's my next step to destroy the old cache so it doesn't waste space?
| Reverse "lvconvert --splitcache"? |
Disable absolute volume in Pulseaudio's config.
Edit the file
/etc/pulse/default.paAnd change the line
load-module module-bluetooth-discoverto
load-module module-bluetooth-discover avrcp_absolute_volume=falseCredit for this solution goes to https://www.reddit.com/user/mmstick/
https://www.reddit.com/r/pop_os/comments/s2y0hf/pop_os_2110_brake_bluetooth_device_volume_control/Unfortunately the above solution stopped working for me (kernel 5.19.0-76051900-generic)
But I found another solution that works for me currently: https://askubuntu.com/a/1350436
|
$ neofetch
OS: Pop!_OS 21.10 x86_64
Kernel: 5.15.8-76051508-genericI have two Bluetooth devices: a speaker SoundCore Boost and headphones EDIFIER W830BT.
When I'm trying to change the volume on headphones using system volume settings it does work. Headphones also have buttons on them for controlling volume and those buttons also work (they change system volume in Linux).
But on a Bluetooth speaker changing volume in Linux doesn't affect the actual volume. On the other hand, using volume buttons on the speaker does change the system volume in Linux (and the volume level bar in Linux changes as expected when I use the device's buttons).
Also, when I mute system volume in Linux it does affect the speaker (sound mutes).
Summarizing - Bluetooth devices work, sound plays, I can change volumes using devices' buttons but only the speaker volume can't be controlled via Linux system volume (except muting).
I removed and paired again the speaker but that didn't help.
For both devices, Output Device configuration is set to Hight Fidelity Playback (A2DP Sink).
The same speaker works well on macOS (changing system volume affects the speaker volume).
$ bluetoothctl devices
Device 00:22:37:59:E0:A5 SoundCore Boost
Device 5C:C6:E9:30:68:EA EDIFIER W830BT$ bluetoothctl show
Controller 38:DE:AD:1B:85:90 (public)
Name: xxxx
Alias: xxxx
Class: 0x007c010c
Powered: yes
Discoverable: no
DiscoverableTimeout: 0x000000b4
Pairable: no
UUID: Message Notification Se.. (00001133-0000-1000-8000-00805f9b34fb)
UUID: A/V Remote Control (0000110e-0000-1000-8000-00805f9b34fb)
UUID: OBEX Object Push (00001105-0000-1000-8000-00805f9b34fb)
UUID: Message Access Server (00001132-0000-1000-8000-00805f9b34fb)
UUID: PnP Information (00001200-0000-1000-8000-00805f9b34fb)
UUID: IrMC Sync (00001104-0000-1000-8000-00805f9b34fb)
UUID: Vendor specific (00005005-0000-1000-8000-0002ee000001)
UUID: Headset (00001108-0000-1000-8000-00805f9b34fb)
UUID: A/V Remote Control Target (0000110c-0000-1000-8000-00805f9b34fb)
UUID: Generic Attribute Profile (00001801-0000-1000-8000-00805f9b34fb)
UUID: Phonebook Access Server (0000112f-0000-1000-8000-00805f9b34fb)
UUID: Device Information (0000180a-0000-1000-8000-00805f9b34fb)
UUID: Audio Sink (0000110b-0000-1000-8000-00805f9b34fb)
UUID: Generic Access Profile (00001800-0000-1000-8000-00805f9b34fb)
UUID: Handsfree Audio Gateway (0000111f-0000-1000-8000-00805f9b34fb)
UUID: Audio Source (0000110a-0000-1000-8000-00805f9b34fb)
UUID: OBEX File Transfer (00001106-0000-1000-8000-00805f9b34fb)
Modalias: usb:v1D6Bp0246d053C
Discovering: no
Roles: central
Roles: peripheral
Advertising Features:
ActiveInstances: 0x00 (0)
SupportedInstances: 0x05 (5)
SupportedIncludes: tx-power
SupportedIncludes: appearance
SupportedIncludes: local-nameAny ideas on how to solve the problem?Edit 1:
I booted live LTS version with an older kernel
$ neofetch
OS: Pop!_OS 20.04 LTS x86_64
Kernel: 5.13.0-7620-genericAnd it turned out that there's no issue with that version - system sound control affects the volume of my Bluetooth speaker as expected.
I also booted the live version of my current system (to confirm that there's no issue with my installed version) and the issue with volume control was present.
So my guess is that kernel 5.15.8-76051508-generic does something with Bluetooth and sound control differently than 5.13.0-7620-generic.Edit 2:
I downgraded the kernel version to 5.13.0.
https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.13/
I downloaded 4 files and installed them
$ ls
linux-headers-xxx_all.deb
linux-headers-xxx-generic_xxx.deb
linux-image-usigned-xxx-generic_xxx.deb
linux-modules-xxx-generic_xxx.deb$ sudo dpkg -i *.debPop!_OS doesn't have GRUB and uses kernelstub
https://github.com/isantop/kernelstub/blob/master/README.md
I changed the kernel version using the following command (where xxx is the desired kernel version)
$ sudo kernelstub -v -k /boot/vmlinuz-xxx-generic -i /boot/initrd.img-xxx-genericAfter the reboot, I see that I'm using kernel 5.13.0-051300-generic but that doesn't solve the problem with volume control.
$ uname -r
5.13.0-051300-genericSo my guess is that Pop!_OS changed something between 20.04 LTS and 21.10 that broke proper volume control in my Bluetooth speaker and it's not the kernel's fault.
| Bluetooth speaker volume control doesn't work (but muting does work) |
ERROR: type should be string, got "\nhttps://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Per-application_volumes_change_when_the_Master_volume_is_adjusted\nIt's a pulseaudio default setting to link all the volumes together. Setting\nflat-volumes = noin /etc/pulse/daemon.conf should fix that!\n" |
This is something that has been bugging me for awhile and I haven't been able to find a fix yet. Whenever I change the system volume using the hardware volume keys on my laptop, it also changes the Spotify volume (it moves the Spotify volume slider as well as the system volume slider). Is there a way to prevent this from occurring? I've searched around for awhile and haven't found anything.
I have looked at Arch's awesome wiki, but I haven't found anything that helped the problem. A similar issue is described here on the wiki, but it didn't solve the problem.
This issue has occurred on all the desktop environments I've used on Arch so far. XFCE, Gnome, and Cinnamon (what I'm currently using) all suffer from this. I believe I am using pulseaudio for my audio server. I am also using the Linux Preview of Spotify which I installed from the AUR.
If someone posts a solution that works, I will be sure to add it to the Arch Wiki for others to reference.
| Changing system volume also changes Spotify volume (Arch Linux) |
Most importantly, you can't have an LV spanning two different VGs.
Also, there's no tool to move a logical volume to a different volume group. You can do it indirectly by creating a LV on the target VG, deactivating the source LV, copying the raw content, and activating the target LV. And there's no tool to move a physical volume to a different volume group. You can do it indirectly by moving all LVs that use the PV to different PVs (with pvmove), then removing the PV from the old VG and adding it to the new one.
These are reasons to have a single VG.
On the other hand, if you're ever planning to run your machine with only one batch of disks (perhaps because the 2TB drive has failed), this will be easier if the VG is still whole.
When you create a LV, you can choose which PVs it's on, but it's more cumbersome than letting it fall wherever it wants on the VG.
Given that the disk sets are intended to contain different types of files, I'd go for separate VGs.
You can make maintenance slightly easier if you ever need to shuffle VGs around by splitting each disk into several PVs. That way you have a chance of freeing one of the PVs in a VG to move it to a different VG. While you can shrink a PV (to allocate the freed space to a new PV in a different VG), it's somewhat cumbersome.
|
I currently have 3x1TB physical volumes in a VG and a LV that spans the entire capacity of the VG. This LV is meant to store specific files.
Now I have another 2TB drive that I want to use LVM with. This will end up being part of an LV (again, using max capacity) that will be used to store different kinds of files.
Should I create a new VG for the 2TB drive and another LV from that new VG? I plan on adding other 2TB drives to the mix later on, does that change the setup I should have? What are the best practises when it comes to LVM and VGs/LVs?
| When should I create a new volume group instead of a new logical volume? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.