github.com/matrixorigin/matrixone@v1.2.0/pkg/vm/engine/tae/db/lock.go (about)

     1  // Copyright 2021 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package db
    16  
    17  import (
    18  	"io"
    19  	"os"
    20  	"syscall"
    21  
    22  	"github.com/matrixorigin/matrixone/pkg/logutil"
    23  	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/db/dbutils"
    24  )
    25  
    26  const (
    27  	LockName string = "TAE"
    28  )
    29  
    30  // createDBLock creates a file lock on TAE's working directory.
    31  func createDBLock(dir string) (io.Closer, error) {
    32  	if _, err := os.Stat(dir); os.IsNotExist(err) {
    33  		err = os.MkdirAll(dir, 0755)
    34  		if err != nil {
    35  			return nil, err
    36  		}
    37  	}
    38  	fname := dbutils.MakeLockFileName(dir, LockName)
    39  	f, err := os.Create(fname)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  	flockT := syscall.Flock_t{
    44  		Type:   syscall.F_WRLCK,
    45  		Whence: io.SeekStart,
    46  		Start:  0,
    47  		Len:    0,
    48  		Pid:    int32(os.Getpid()),
    49  	}
    50  	if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &flockT); err != nil {
    51  		logutil.Errorf("error locking file: %s", err)
    52  		f.Close()
    53  		return nil, err
    54  	}
    55  	return f, nil
    56  }