github.com/openebs/node-disk-manager@v1.9.1-0.20230225014141-4531f06ffa1e/api-service/node/services/hugepages.go (about) 1 /* 2 Copyright 2020 The OpenEBS Authors 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 http://www.apache.org/licenses/LICENSE-2.0 7 Unless required by applicable law or agreed to in writing, software 8 distributed under the License is distributed on an "AS IS" BASIS, 9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 See the License for the specific language governing permissions and 11 limitations under the License. 12 */ 13 14 package services 15 16 import ( 17 "context" 18 "io/ioutil" 19 "strconv" 20 "strings" 21 22 protos "github.com/openebs/node-disk-manager/spec/ndm" 23 24 "google.golang.org/grpc/codes" 25 "google.golang.org/grpc/status" 26 "k8s.io/klog/v2" 27 ) 28 29 const hugepagesPath = "/sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages" 30 31 // SetHugepages service can set 2MB hugepages on a node 32 func (n *Node) SetHugepages(ctx context.Context, h *protos.Hugepages) (*protos.HugepagesResult, error) { 33 34 // Note: Calling this method doesn't guarantee that the said number of pages will be set. 35 // This is because OS might not have the demanded memory. It would be best to check if this is satisfied with GetHugePages() 36 37 klog.Info("Setting Hugepages") 38 39 hugepages := protos.Hugepages{ 40 Pages: h.Pages, 41 } 42 43 msg := []byte(strconv.Itoa(int(hugepages.Pages))) 44 err := ioutil.WriteFile(hugepagesPath, msg, 0644) 45 if err != nil { 46 klog.Errorf("Error setting huge pages: %v", err) 47 return nil, status.Errorf(codes.Internal, "Error setting hugepages") 48 } 49 50 return &protos.HugepagesResult{Result: true}, nil 51 } 52 53 // GetHugepages services gets the number of hugepages on a node 54 func (n *Node) GetHugepages(ctx context.Context, null *protos.Null) (*protos.Hugepages, error) { 55 56 klog.Info("Getting the number of hugepages") 57 58 hugepages, err := ioutil.ReadFile(hugepagesPath) 59 if err != nil { 60 klog.Errorf("Error fetching number of hugepages %v", err) 61 return nil, status.Errorf(codes.Internal, "Error fetching the number of hugepages set on the node") 62 } 63 64 pages, err := strconv.ParseInt(strings.TrimRight(string(hugepages), "\n"), 10, 32) 65 if err != nil { 66 klog.Errorf("Error converting number of hugepages %v", err) 67 return nil, status.Errorf(codes.Internal, "Error converting the number of hugepages set on the node") 68 } 69 70 return &protos.Hugepages{ 71 Pages: int32(pages), 72 }, nil 73 }