go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/resources/lsblk.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package resources
     5  
     6  import (
     7  	"encoding/json"
     8  	"errors"
     9  
    10  	"go.mondoo.com/cnquery/llx"
    11  	"go.mondoo.com/cnquery/types"
    12  )
    13  
    14  func (l *mqlLsblk) id() (string, error) {
    15  	return "lsblk", nil
    16  }
    17  
    18  func (l *mqlLsblk) list() ([]interface{}, error) {
    19  	o, err := CreateResource(l.MqlRuntime, "command", map[string]*llx.RawData{
    20  		"command": llx.StringData("lsblk --json --fs"),
    21  	})
    22  	cmd := o.(*mqlCommand)
    23  	if exit := cmd.GetExitcode(); exit.Data != 0 {
    24  		return nil, errors.New("could not retrieve lsblk: " + cmd.Stderr.Data)
    25  	}
    26  
    27  	blockEntries, err := parseBlockEntries([]byte(cmd.Stdout.Data))
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	mqlBlockEntries := []interface{}{}
    33  	for i := range blockEntries.Blockdevices {
    34  		d := blockEntries.Blockdevices[i]
    35  		for i := range d.Children {
    36  			entry := d.Children[i]
    37  			entry.Mountpoints = append(entry.Mountpoints, entry.Mountpoint)
    38  			mqlLsblkEntry, err := CreateResource(l.MqlRuntime, "lsblk.entry", map[string]*llx.RawData{
    39  				"name":        llx.StringData(entry.Name),
    40  				"fstype":      llx.StringData(entry.Fstype),
    41  				"label":       llx.StringData(entry.Label),
    42  				"uuid":        llx.StringData(entry.Uuid),
    43  				"mountpoints": llx.ArrayData(entry.Mountpoints, types.String),
    44  			})
    45  			if err != nil {
    46  				return nil, err
    47  			}
    48  			mqlBlockEntries = append(mqlBlockEntries, mqlLsblkEntry)
    49  		}
    50  	}
    51  	return mqlBlockEntries, nil
    52  }
    53  
    54  func parseBlockEntries(data []byte) (blockdevices, error) {
    55  	blockEntries := blockdevices{}
    56  	if err := json.Unmarshal(data, &blockEntries); err != nil {
    57  		return blockEntries, err
    58  	}
    59  	return blockEntries, nil
    60  }
    61  
    62  func (l *mqlLsblkEntry) id() (string, error) {
    63  	return l.Name.Data + "-" + l.Fstype.Data, nil
    64  }
    65  
    66  type blockdevices struct {
    67  	Blockdevices []blockdevice `json:"blockdevices,omitempty"`
    68  }
    69  
    70  type blockdevice struct {
    71  	Name        string        `json:"name,omitempty"`
    72  	Fstype      string        `json:"fstype,omitempty"`
    73  	Label       string        `json:"label,omitempty"`
    74  	Uuid        string        `json:"uuid,omitempty"`
    75  	Mountpoints []interface{} `json:"mountpoints,omitempty"`
    76  	Mountpoint  string        `json:"mountpoint,omitempty"`
    77  	Children    []blockdevice `json:"children,omitempty"`
    78  }