@@ -456,8 +456,24 @@ func reserveSocket(protocol, hostAddr string) (*os.File, error) {
456456}
457457
458458// portReserverPidFilePath returns /run/nerdctl/<namespace>/<id>/port-reserver.pid
459- func portReserverPidFilePath (opts * handlerOpts ) string {
460- return filepath .Join ("/run/nerdctl/" , opts .state .Annotations [labels .Namespace ], opts .state .ID , "port-reserver.pid" )
459+ func portReserverPidFilePath (namespace , id string ) string {
460+ return filepath .Join ("/run/nerdctl/" , namespace , id , "port-reserver.pid" )
461+ }
462+
463+ func CleanupPortReserverProcess (namespace , id string ) error {
464+ // In rootless mode, port-reserver is handled by Rootlesskit, so no cleanup is needed.
465+ if rootlessutil .IsRootlessChild () {
466+ return nil
467+ }
468+
469+ pidFile := portReserverPidFilePath (namespace , id )
470+ if err := killProcessByPidFile (pidFile ); err != nil {
471+ return err
472+ }
473+ if err := os .RemoveAll (filepath .Dir (pidFile )); err != nil {
474+ log .L .WithError (err ).Errorf ("failed to remove the port-reserver directory %s" , filepath .Dir (pidFile ))
475+ }
476+ return nil
461477}
462478
463479func applyNetworkSettings (opts * handlerOpts ) (err error ) {
@@ -503,10 +519,10 @@ func applyNetworkSettings(opts *handlerOpts) (err error) {
503519 if err != nil {
504520 log .L .Debugf ("killing the port reserver process (pid=%d)" , reserverCmdPid )
505521 _ = reserverCmd .Process .Kill ()
506- _ = os .RemoveAll (filepath .Dir (portReserverPidFilePath (opts )))
522+ _ = os .RemoveAll (filepath .Dir (portReserverPidFilePath (opts . state . Annotations [ labels . Namespace ], opts . state . ID )))
507523 }
508524 }()
509- if err := writePidFile (portReserverPidFilePath (opts ), reserverCmdPid ); err != nil {
525+ if err := writePidFile (portReserverPidFilePath (opts . state . Annotations [ labels . Namespace ], opts . state . ID ), reserverCmdPid ); err != nil {
510526 return fmt .Errorf ("cannot write the pid file of the port reserver process: %w" , err )
511527 }
512528 }
@@ -745,13 +761,9 @@ func onPostStop(opts *handlerOpts) error {
745761 return fmt .Errorf ("failed to release container name %s: %w" , name , err )
746762 }
747763 // Kill port-reserver process if any
748- portReserverPidFile := portReserverPidFilePath (opts )
749- if err = killProcessByPidFile (portReserverPidFile ); err != nil {
764+ if err = CleanupPortReserverProcess (ns , opts .state .ID ); err != nil {
750765 log .L .WithError (err ).Errorf ("failed to kill the port-reserver process" )
751766 }
752- if err := os .RemoveAll (filepath .Dir (portReserverPidFile )); err != nil {
753- log .L .WithError (err ).Errorf ("failed to remove the port-reserver directory %s" , filepath .Dir (portReserverPidFile ))
754- }
755767 return nil
756768}
757769
0 commit comments