How to use Info method of qemu Package

Best Syzkaller code snippet using qemu.Info

qemu.go

Source:qemu.go Github

copy

Full Screen

...35 maxMemory = 1 << 30 //value from OpenStack Nova36 maxCPUSecs = 30 //value from OpenStack Nova37 matcherString = "\\((\\d?\\d\\.\\d\\d)\\/100%\\)"38)39// ImgInfo contains the virtual image information.40type ImgInfo struct {41 // Format contains the format of the image42 Format string `json:"format"`43 // BackingFile is the file name of the backing file44 BackingFile string `json:"backing-filename"`45 // VirtualSize is the disk size of the image which will be read by vm46 VirtualSize int64 `json:"virtual-size"`47 // ActualSize is the size of the qcow2 image48 ActualSize int64 `json:"actual-size"`49}50// QEMUOperations defines the interface for executing qemu subprocesses51type QEMUOperations interface {52 ConvertToRawStream(*url.URL, string, bool) error53 Resize(string, resource.Quantity, bool) error54 Info(url *url.URL) (*ImgInfo, error)55 Validate(*url.URL, int64, float64) error56 CreateBlankImage(string, resource.Quantity, bool) error57 Rebase(backingFile string, delta string) error58 Commit(image string) error59}60type qemuOperations struct{}61var (62 qemuExecFunction = system.ExecWithLimits63 qemuInfoLimits = &system.ProcessLimitValues{AddressSpaceLimit: maxMemory, CPUTimeLimit: maxCPUSecs}64 qemuIterface = NewQEMUOperations()65 re = regexp.MustCompile(matcherString)66 progress = prometheus.NewCounterVec(67 prometheus.CounterOpts{68 Name: "import_progress",69 Help: "The import progress in percentage",70 },71 []string{"ownerUID"},72 )73 ownerUID string74 convertPreallocationMethods = [][]string{75 {"-o", "preallocation=falloc"},76 {"-o", "preallocation=full"},77 {"-S", "0"},78 }79 resizePreallocationMethods = [][]string{80 {"--preallocation=falloc"},81 {"--preallocation=full"},82 }83)84func init() {85 if err := prometheus.Register(progress); err != nil {86 if are, ok := err.(prometheus.AlreadyRegisteredError); ok {87 // A counter for that metric has been registered before.88 // Use the old counter from now on.89 progress = are.ExistingCollector.(*prometheus.CounterVec)90 } else {91 klog.Errorf("Unable to create prometheus progress counter")92 }93 }94 ownerUID, _ = util.ParseEnvVar(common.OwnerUID, false)95}96// NewQEMUOperations returns the default implementation of QEMUOperations97func NewQEMUOperations() QEMUOperations {98 return &qemuOperations{}99}100func convertToRaw(src, dest string, preallocate bool) error {101 args := []string{"convert", "-t", "writeback", "-p", "-O", "raw", src, dest}102 var err error103 if preallocate {104 err = addPreallocation(args, convertPreallocationMethods, func(args []string) ([]byte, error) {105 return qemuExecFunction(nil, reportProgress, "qemu-img", args...)106 })107 } else {108 klog.V(3).Infof("Running qemu-img convert with args: %v", args)109 _, err = qemuExecFunction(nil, reportProgress, "qemu-img", args...)110 }111 if err != nil {112 os.Remove(dest)113 errorMsg := "could not convert image to raw"114 if nbdkitLog, err := ioutil.ReadFile(common.NbdkitLogPath); err == nil {115 errorMsg += " " + string(nbdkitLog)116 }117 return errors.Wrap(err, errorMsg)118 }119 // With writeback cache mode it's possible that the process will exit before all writes have been commited to storage.120 // To guarantee that our write was commited to storage, we make a fsync syscall and ensure success.121 file, err := os.Open(dest)122 if err != nil {123 return errors.Wrap(err, "could not get file descriptor for fsync call following qemu-img writing")124 }125 if err := file.Sync(); err != nil {126 return errors.Wrap(err, "could not fsync following qemu-img writing")127 }128 klog.V(3).Infof("Successfully completed fsync(%s) syscall, qemu-img convert write is commited to disk", dest)129 file.Close()130 return nil131}132func (o *qemuOperations) ConvertToRawStream(url *url.URL, dest string, preallocate bool) error {133 if len(url.Scheme) > 0 && url.Scheme != "nbd+unix" {134 return fmt.Errorf("not valid schema %s", url.Scheme)135 }136 return convertToRaw(url.String(), dest, preallocate)137}138// convertQuantityToQemuSize translates a quantity string into a Qemu compatible string.139func convertQuantityToQemuSize(size resource.Quantity) string {140 int64Size, asInt := size.AsInt64()141 if !asInt {142 size.AsDec().SetScale(0)143 return size.AsDec().String()144 }145 return strconv.FormatInt(int64Size, 10)146}147// Resize resizes the given image to size148func Resize(image string, size resource.Quantity, preallocate bool) error {149 return qemuIterface.Resize(image, size, preallocate)150}151func (o *qemuOperations) Resize(image string, size resource.Quantity, preallocate bool) error {152 var err error153 args := []string{"resize", "-f", "raw", image, convertQuantityToQemuSize(size)}154 if preallocate {155 err = addPreallocation(args, resizePreallocationMethods, func(args []string) ([]byte, error) {156 return qemuExecFunction(nil, nil, "qemu-img", args...)157 })158 } else {159 _, err = qemuExecFunction(nil, nil, "qemu-img", args...)160 }161 if err != nil {162 return errors.Wrapf(err, "Error resizing image %s", image)163 }164 return nil165}166func checkOutputQemuImgInfo(output []byte, image string) (*ImgInfo, error) {167 var info ImgInfo168 err := json.Unmarshal(output, &info)169 if err != nil {170 klog.Errorf("Invalid JSON:\n%s\n", string(output))171 return nil, errors.Wrapf(err, "Invalid json for image %s", image)172 }173 return &info, nil174}175// Info returns information about the image from the url176func Info(url *url.URL) (*ImgInfo, error) {177 return qemuIterface.Info(url)178}179func (o *qemuOperations) Info(url *url.URL) (*ImgInfo, error) {180 if len(url.Scheme) > 0 && url.Scheme != "nbd+unix" {181 return nil, fmt.Errorf("not valid schema %s", url.Scheme)182 }183 output, err := qemuExecFunction(qemuInfoLimits, nil, "qemu-img", "info", "--output=json", url.String())184 if err != nil {185 errorMsg := fmt.Sprintf("%s, %s", output, err.Error())186 if nbdkitLog, err := ioutil.ReadFile(common.NbdkitLogPath); err == nil {187 errorMsg += " " + string(nbdkitLog)188 }189 return nil, errors.Errorf(errorMsg)190 }191 return checkOutputQemuImgInfo(output, url.String())192}193func isSupportedFormat(value string) bool {194 switch value {195 case "raw", "qcow2", "vmdk", "vdi", "vpc", "vhdx":196 return true197 default:198 return false199 }200}201func checkIfURLIsValid(info *ImgInfo, availableSize int64, filesystemOverhead float64, image string) error {202 if !isSupportedFormat(info.Format) {203 return errors.Errorf("Invalid format %s for image %s", info.Format, image)204 }205 if len(info.BackingFile) > 0 {206 if _, err := os.Stat(info.BackingFile); err != nil {207 return errors.Errorf("Image %s is invalid because it has invalid backing file %s", image, info.BackingFile)208 }209 }210 if int64(float64(availableSize)*(1-filesystemOverhead)) < info.VirtualSize {211 return errors.Errorf("Virtual image size %d is larger than available size %d (PVC size %d, reserved overhead %f%%). A larger PVC is required.", info.VirtualSize, int64((1-filesystemOverhead)*float64(availableSize)), info.VirtualSize, filesystemOverhead)212 }213 return nil214}215func (o *qemuOperations) Validate(url *url.URL, availableSize int64, filesystemOverhead float64) error {216 info, err := o.Info(url)217 if err != nil {218 return err219 }220 return checkIfURLIsValid(info, availableSize, filesystemOverhead, url.String())221}222// ConvertToRawStream converts an http accessible image to raw format without locally caching the image223func ConvertToRawStream(url *url.URL, dest string, preallocate bool) error {224 return qemuIterface.ConvertToRawStream(url, dest, preallocate)225}226// Validate does basic validation of a qemu image227func Validate(url *url.URL, availableSize int64, filesystemOverhead float64) error {228 return qemuIterface.Validate(url, availableSize, filesystemOverhead)229}230func reportProgress(line string) {231 // (45.34/100%)232 matches := re.FindStringSubmatch(line)233 if len(matches) == 2 && ownerUID != "" {234 klog.V(1).Info(matches[1])235 // Don't need to check for an error, the regex made sure its a number we can parse.236 v, _ := strconv.ParseFloat(matches[1], 64)237 metric := &dto.Metric{}238 err := progress.WithLabelValues(ownerUID).Write(metric)239 if err == nil && v > 0 && v > *metric.Counter.Value {240 progress.WithLabelValues(ownerUID).Add(v - *metric.Counter.Value)241 }242 }243}244// CreateBlankImage creates empty raw image245func CreateBlankImage(dest string, size resource.Quantity, preallocate bool) error {246 klog.V(1).Infof("creating raw image with size %s, preallocation %v", size.String(), preallocate)247 return qemuIterface.CreateBlankImage(dest, size, preallocate)248}249// CreateBlankImage creates a raw image with a given size250func (o *qemuOperations) CreateBlankImage(dest string, size resource.Quantity, preallocate bool) error {251 klog.V(3).Infof("image size is %s", size.String())252 args := []string{"create", "-f", "raw", dest, convertQuantityToQemuSize(size)}253 if preallocate {254 klog.V(1).Infof("Added preallocation")255 args = append(args, []string{"-o", "preallocation=falloc"}...)256 }257 _, err := qemuExecFunction(nil, nil, "qemu-img", args...)258 if err != nil {259 os.Remove(dest)260 return errors.Wrap(err, fmt.Sprintf("could not create raw image with size %s in %s", size.String(), dest))261 }262 // Change permissions to 0660263 err = os.Chmod(dest, 0660)264 if err != nil {265 err = errors.Wrap(err, "Unable to change permissions of target file")266 }267 return nil268}269func execPreallocation(dest string, bs, count, offset int64) error {270 args := []string{"if=/dev/zero", "of=" + dest, fmt.Sprintf("bs=%d", bs), fmt.Sprintf("count=%d", count), fmt.Sprintf("seek=%d", offset), "oflag=seek_bytes"}271 _, err := qemuExecFunction(nil, nil, "dd", args...)272 if err != nil {273 return errors.Wrap(err, fmt.Sprintf("Could not preallocate blank block volume at %s, running dd for size %d, offset %d", dest, bs*count, offset))274 }275 return nil276}277// PreallocateBlankBlock writes requested amount of zeros to block device mounted at dest278func PreallocateBlankBlock(dest string, size resource.Quantity) error {279 klog.V(3).Infof("block volume size is %s", size.String())280 qemuSize, err := strconv.ParseInt(convertQuantityToQemuSize(size), 10, 64)281 if err != nil {282 return errors.Wrap(err, fmt.Sprintf("Could not parse size for preallocating blank block volume at %s with size %s", dest, size.String()))283 }284 countBlocks, remainder := qemuSize/units.MiB, qemuSize%units.MiB285 err = execPreallocation(dest, units.MiB, countBlocks, 0)286 if err != nil {287 return err288 }289 if remainder != 0 {290 return execPreallocation(dest, remainder, 1, countBlocks*units.MiB)291 }292 return nil293}294func addPreallocation(args []string, preallocationMethods [][]string, qemuFn func(args []string) ([]byte, error)) error {295 var err error296 for _, preallocationMethod := range preallocationMethods {297 var output []byte298 klog.V(1).Infof("Adding preallocation method: %v", preallocationMethod)299 // For some subcommands (e.g. resize), preallocation optinos must come before other options300 argsToTry := append([]string{args[0]}, preallocationMethod...)301 argsToTry = append(argsToTry, args[1:]...)302 klog.V(3).Infof("Attempting preallocation method, qemu-img convert args: %v", argsToTry)303 output, err = qemuFn(argsToTry)304 if err != nil && strings.Contains(string(output), "Unsupported preallocation mode") {305 klog.V(1).Infof("Unsupported preallocation mode. Retrying")306 } else {307 break308 }309 }310 return err311}312// Rebase changes a QCOW's backing file to point to a previously-downloaded base image.313// Depends on original image having been downloaded as raw.314func (o *qemuOperations) Rebase(backingFile string, delta string) error {315 klog.V(1).Infof("Rebasing %s onto %s", delta, backingFile)316 args := []string{"rebase", "-p", "-u", "-F", "raw", "-b", backingFile, delta}317 _, err := qemuExecFunction(nil, reportProgress, "qemu-img", args...)318 return err319}320// Commit takes the changes written to a QCOW and applies them to its raw backing file.321func (o *qemuOperations) Commit(image string) error {322 klog.V(1).Infof("Committing %s to backing file...", image)323 args := []string{"commit", "-p", image}324 _, err := qemuExecFunction(nil, reportProgress, "qemu-img", args...)325 return err326}...

Full Screen

Full Screen

Info

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q, err := qmp.Dial("unix", "/tmp/qmp-sock")4 if err != nil {5 panic(err)6 }7 defer q.Close()8 info, err := q.ExecuteQMPCapabilities()9 if err != nil {10 panic(err)11 }12 fmt.Println(info)13}14import (15func main() {16 q, err := qmp.Dial("unix", "/tmp/qmp-sock")17 if err != nil {18 panic(err)19 }20 defer q.Close()21 err = q.ExecuteSystemReset()22 if err != nil {23 panic(err)24 }25}26import (27func main() {28 q, err := qmp.Dial("unix", "/tmp/qmp-sock")29 if err != nil {30 panic(err)31 }32 defer q.Close()33 err = q.ExecuteSystemPowerdown()34 if err != nil {35 panic(err)36 }37}38import (39func main() {40 q, err := qmp.Dial("unix", "/tmp/qmp-sock")41 if err != nil {42 panic(err)43 }44 defer q.Close()45 err = q.ExecuteSystemWakeup()46 if err != nil {47 panic(err)48 }49}50import (51func main() {52 q, err := qmp.Dial("unix", "/tmp/qmp-sock")53 if err != nil {54 panic(err)55 }56 defer q.Close()57 err = q.ExecuteStop()58 if err != nil {59 panic(err)60 }61}

Full Screen

Full Screen

Info

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q := qemu.NewQemu("/usr/bin/qemu-system-x86_64", true)4 defer q.Disconnect()5 err := q.Connect()6 if err != nil {7 fmt.Println(err)8 }9 info, err := q.Info()10 if err != nil {

Full Screen

Full Screen

Info

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q := qemu.NewQemu()4 err := q.Info()5 if err != nil {6 fmt.Println(err)7 }8}9QEMU emulator version 2.1.0 (qemu-2.1.0-1.fc22)10import (11func main() {12 q := qemu.NewQemu()13 err := q.InfoAsync()14 if err != nil {15 fmt.Println(err)16 }17 time.Sleep(1 * time.Second)18 q.Close()19}20QEMU emulator version 2.1.0 (qemu-2.1.0-1.fc22)21You can also use the InfoAsync() method to execute more than one command. For example, to get the version and the list of the VMs running:22import (23func main() {24 q := qemu.NewQemu()25 err := q.InfoAsync()26 if err != nil {27 fmt.Println(err)28 }29 time.Sleep(1 * time.Second)30 q.InfoAsync()31 time.Sleep(1 * time.Second)32 q.Close()33}

Full Screen

Full Screen

Info

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 qemu := qemu.NewQemu("/var/run/qemu.pid")4 info, err := qemu.Info()5 if err != nil {6 panic(err)7 }8 fmt.Printf("Version: %s9 fmt.Printf("KVM: %t10 fmt.Printf("Max CPUs: %d11 fmt.Printf("CPUs: %d12 fmt.Printf("Memory: %d13 fmt.Printf("Current Memory: %d14 fmt.Printf("Current Ballooned Memory: %d15 fmt.Printf("Current Live Memory: %d16 fmt.Printf("Migration Downtime: %d17 fmt.Printf("Status: %s18 fmt.Printf("VM status: %s19 fmt.Printf("VM status: %s20 fmt.Printf("VM status: %s21 fmt.Printf("VM status: %s22}

Full Screen

Full Screen

Info

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3q := qemu{2, 4, 6}4q.Info()5}6import "fmt"7func main() {8q := qemu{2, 4, 6}9q.Info()10}11import "fmt"12func main() {13q := qemu{2, 4, 6}14q.Info()15}16import "fmt"17func main() {18q := qemu{2, 4, 6}19q.Info()20}21import "fmt"22func main() {23q := qemu{2, 4, 6}24q.Info()25}26import "fmt"27func main() {28q := qemu{2, 4, 6}29q.Info()30}31import "fmt"32func main() {33q := qemu{2, 4, 6}34q.Info()35}36import "fmt"37func main() {38q := qemu{2, 4, 6}39q.Info()40}

Full Screen

Full Screen

Info

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main(){3 fmt.Println("Path: 2.go")4 q.Info()5}6import "fmt"7func main(){8 fmt.Println("Path: 1.go")9 q.Info()10}11import "fmt"12func main(){13 fmt.Println("Path: 3.go")14 q.Info()15}16import "fmt"17type qemu struct{18}19func (q *qemu) Info(){20 fmt.Println("Path: qemu.go")21 fmt.Println("qemu class")22}23import "fmt"24func main(){25 fmt.Println("Path: 4.go")26 q.Info()27}28import "fmt"29func main(){30 fmt.Println("Path: 5.go")31 q.Info()32}33import "fmt"34func main(){35 fmt.Println("Path: 6.go")36 q.Info()37}38import "fmt"39func main(){40 fmt.Println("Path: 7.go")41 q.Info()42}43import "fmt"44func main(){45 fmt.Println("Path: 8.go")

Full Screen

Full Screen

Info

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q := qemu{4 }5 q.Info()6}7type Derived struct {8}9import (10type qemu struct {11}12type kvm struct {13}14func main() {15 k := kvm{16 qemu: qemu{17 },18 }19 fmt.Println(k.qemu)20}21{kvm 2.8.0 x86_64 linux}

Full Screen

Full Screen

Info

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q := qemu{}4 q.Info()5}6import (7func main() {8 q := qemu{}9 q.Info()10}11import (12func main() {13 q := qemu{}14 q.Info()15}16import (17func main() {18 q := qemu{}19 q.Info()20}21import (22func main() {23 q := qemu{}24 q.Info()25}26import (27func main() {28 q := qemu{}29 q.Info()30}31import (32func main() {33 q := qemu{}34 q.Info()35}36import (37func main() {38 q := qemu{}39 q.Info()40}41import (

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful