vitess.io/vitess@v0.16.2/go/vt/servenv/pid_file.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package servenv
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  
    23  	"vitess.io/vitess/go/vt/log"
    24  )
    25  
    26  var pidFile string // registered in RegisterFlags as --pid_file
    27  
    28  func init() {
    29  	pidFileCreated := false
    30  
    31  	// Create pid file after flags are parsed.
    32  	OnInit(func() {
    33  		if pidFile == "" {
    34  			return
    35  		}
    36  
    37  		file, err := os.OpenFile(pidFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
    38  		if err != nil {
    39  			log.Errorf("Unable to create pid file '%s': %v", pidFile, err)
    40  			return
    41  		}
    42  		pidFileCreated = true
    43  		fmt.Fprintln(file, os.Getpid())
    44  		file.Close()
    45  	})
    46  
    47  	// Remove pid file on graceful shutdown.
    48  	OnClose(func() {
    49  		if pidFile == "" {
    50  			return
    51  		}
    52  		if !pidFileCreated {
    53  			return
    54  		}
    55  
    56  		if err := os.Remove(pidFile); err != nil {
    57  			log.Errorf("Unable to remove pid file '%s': %v", pidFile, err)
    58  		}
    59  	})
    60  }