├── .buildkite ├── hooks │ ├── pre-checkout │ └── pre-exit └── pipeline.yml ├── .github ├── CODEOWNERS ├── PULL_REQUEST_TEMPLATE.md ├── dependabot.yml └── workflows │ └── go.yml ├── .gitignore ├── .hack ├── go.mod └── go.sum ├── .headers ├── go.txt └── makefile.txt ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── COPYRIGHT_HEADER ├── HACKING.md ├── LICENSE ├── Makefile ├── NOTICE ├── README.md ├── balloon.go ├── balloon_test.go ├── benchmark_test.go ├── client ├── firecracker_client.go ├── models │ ├── balloon.go │ ├── balloon_stats.go │ ├── balloon_stats_update.go │ ├── balloon_update.go │ ├── boot_source.go │ ├── cpu_config.go │ ├── cpu_template.go │ ├── drive.go │ ├── entropy_device.go │ ├── error.go │ ├── firecracker_version.go │ ├── full_vm_configuration.go │ ├── instance_action_info.go │ ├── instance_info.go │ ├── logger.go │ ├── machine_configuration.go │ ├── memory_backend.go │ ├── metrics.go │ ├── mmds_config.go │ ├── mmds_contents_object.go │ ├── network_interface.go │ ├── partial_drive.go │ ├── partial_network_interface.go │ ├── rate_limiter.go │ ├── snapshot_create_params.go │ ├── snapshot_load_params.go │ ├── token_bucket.go │ ├── vm.go │ └── vsock.go ├── operations │ ├── create_snapshot_parameters.go │ ├── create_snapshot_responses.go │ ├── create_sync_action_parameters.go │ ├── create_sync_action_responses.go │ ├── describe_balloon_config_parameters.go │ ├── describe_balloon_config_responses.go │ ├── describe_balloon_stats_parameters.go │ ├── describe_balloon_stats_responses.go │ ├── describe_instance_parameters.go │ ├── describe_instance_responses.go │ ├── get_export_vm_config_parameters.go │ ├── get_export_vm_config_responses.go │ ├── get_firecracker_version_parameters.go │ ├── get_firecracker_version_responses.go │ ├── get_machine_configuration_parameters.go │ ├── get_machine_configuration_responses.go │ ├── get_mmds_parameters.go │ ├── get_mmds_responses.go │ ├── load_snapshot_parameters.go │ ├── load_snapshot_responses.go │ ├── operations_client.go │ ├── patch_balloon_parameters.go │ ├── patch_balloon_responses.go │ ├── patch_balloon_stats_interval_parameters.go │ ├── patch_balloon_stats_interval_responses.go │ ├── patch_guest_drive_by_id_parameters.go │ ├── patch_guest_drive_by_id_responses.go │ ├── patch_guest_network_interface_by_id_parameters.go │ ├── patch_guest_network_interface_by_id_responses.go │ ├── patch_machine_configuration_parameters.go │ ├── patch_machine_configuration_responses.go │ ├── patch_mmds_parameters.go │ ├── patch_mmds_responses.go │ ├── patch_vm_parameters.go │ ├── patch_vm_responses.go │ ├── put_balloon_parameters.go │ ├── put_balloon_responses.go │ ├── put_cpu_configuration_parameters.go │ ├── put_cpu_configuration_responses.go │ ├── put_entropy_device_parameters.go │ ├── put_entropy_device_responses.go │ ├── put_guest_boot_source_parameters.go │ ├── put_guest_boot_source_responses.go │ ├── put_guest_drive_by_id_parameters.go │ ├── put_guest_drive_by_id_responses.go │ ├── put_guest_network_interface_by_id_parameters.go │ ├── put_guest_network_interface_by_id_responses.go │ ├── put_guest_vsock_parameters.go │ ├── put_guest_vsock_responses.go │ ├── put_logger_parameters.go │ ├── put_logger_responses.go │ ├── put_machine_configuration_parameters.go │ ├── put_machine_configuration_responses.go │ ├── put_metrics_parameters.go │ ├── put_metrics_responses.go │ ├── put_mmds_config_parameters.go │ ├── put_mmds_config_responses.go │ ├── put_mmds_parameters.go │ └── put_mmds_responses.go └── swagger.yaml ├── client_transports.go ├── client_transports_test.go ├── cni ├── internal │ ├── cniutil.go │ ├── cniutil_test.go │ ├── mocks.go │ └── netlink.go └── vmconf │ ├── vmconf.go │ └── vmconf_test.go ├── command_builder.go ├── command_builder_test.go ├── doc.go ├── docs └── snapshotting.md ├── drives.go ├── drives_test.go ├── example_test.go ├── examples └── cmd │ └── snapshotting │ ├── .gitignore │ ├── .hack │ ├── go.mod │ └── go.sum │ ├── Makefile │ ├── README.md │ ├── example_demo.go │ ├── go.mod │ └── go.sum ├── fctesting ├── firecracker_mock_client.go ├── test_writer.go ├── utils.go └── utils_test.go ├── firecracker.go ├── firecracker_test.go ├── go.mod ├── go.sum ├── go_swagger_layout.yaml ├── handlers.go ├── handlers_test.go ├── internal ├── cpu_template.go └── cpu_template_test.go ├── jailer.go ├── jailer_test.go ├── kernelargs.go ├── kernelargs_test.go ├── machine.go ├── machine_test.go ├── machineiface.go ├── network.go ├── network_test.go ├── opts.go ├── pointer_helpers.go ├── rate_limiter.go ├── rate_limiter_test.go ├── snapshot.go ├── swagger.go ├── templates ├── client │ ├── client.gotmpl │ └── facade.gotmpl └── mockclient.gotmpl ├── testdata ├── drive-2.img ├── drive-3.img └── sigprint.sh ├── utils.go ├── utils_test.go ├── version.go └── vsock ├── dial.go ├── dial_test.go └── listener.go /.buildkite/hooks/pre-checkout: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | set -euo pipefail 3 | 4 | find . -user root -print0 | xargs -0 sudo rm -rf '{}' 5 | -------------------------------------------------------------------------------- /.buildkite/hooks/pre-exit: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | 4 | sudo chown -hR "${USER}:${USER}" . 5 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Global (repository-wide) owners: 2 | * @firecracker-microvm/aws-containers 3 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. 7 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | # Automatic upgrade for Go modules. 4 | - package-ecosystem: "gomod" 5 | directory: "/" 6 | schedule: 7 | interval: "daily" 8 | 9 | # Automatic upgrade for Go modules in examples/cmd/snapshotting 10 | - package-ecosystem: "gomod" 11 | directory: "/examples/cmd/snapshotting" 12 | schedule: 13 | interval: "daily" 14 | ignore: 15 | - dependency-name: "github.com/firecracker-microvm/firecracker-go-sdk" 16 | 17 | # Automatic upgrade for GitHub Actions packages. 18 | - package-ecosystem: "github-actions" 19 | directory: "/" 20 | schedule: 21 | interval: "daily" 22 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | 11 | build: 12 | strategy: 13 | matrix: 14 | go: ['1.23', '1.24'] 15 | os: ['ubuntu-22.04'] 16 | fail-fast: false 17 | name: ${{ matrix.os }} / Go ${{ matrix.go }} 18 | runs-on: ${{ matrix.os }} 19 | steps: 20 | - name: Set up Go 1.x 21 | uses: actions/setup-go@v5 22 | with: 23 | go-version: ${{ matrix.go }} 24 | 25 | - name: Check out code into the Go module directory 26 | uses: actions/checkout@v4 27 | 28 | - name: Test 29 | run: make test EXTRAGOARGS=-v 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | firecracker 2 | jailer 3 | firecracker-* 4 | jailer-* 5 | vmlinux 6 | root-drive.img 7 | TestPID.img 8 | build/ 9 | testdata/fc.stamp 10 | testdata/bin/ 11 | testdata/logs/ 12 | testdata/ltag 13 | testdata/release-* 14 | -------------------------------------------------------------------------------- /.hack/go.mod: -------------------------------------------------------------------------------- 1 | // This is a fake go.mod 2 | // Older versions of go have different go get/go install semantics. In particular: 3 | // 1. `go get` with `GO111MODULES=off` will retrieve and and install a package, but you can't specify a version 4 | // 2. `go get` with `GO111MODULES=on` will retrive a packge at a specific version, but messes with the go.mod. The package can then be installed with `go install` 5 | 6 | // We don't actually want binary dependencies to modify the go.mod but since we want to pin versions, we create this unused go.mod 7 | // that `go get` can mess with without affecting our main codebase. 8 | module hack 9 | 10 | go 1.11 11 | 12 | require ( 13 | github.com/awslabs/tc-redirect-tap v0.0.0-20240408144842-496fddc89db6 // indirect 14 | github.com/containernetworking/plugins v1.1.1 // indirect 15 | github.com/kunalkushwaha/ltag v0.2.3 // indirect 16 | ) 17 | -------------------------------------------------------------------------------- /.headers/go.txt: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | -------------------------------------------------------------------------------- /.headers/makefile.txt: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | # not use this file except in compliance with the License. A copy of the 5 | # License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 1.0.0 2 | * Added support for MMDS version 2. (#441) 3 | * Added support for set drive IO engine type. (#411) 4 | * Added support for get Firecracker version. (#410) 5 | * Added a DriveOpt func for configuring CacheType. (#401) 6 | * Added GetExportVMConfig to read the /vm/config endpoint. (#400) 7 | * Added ability to allow passing cgroup-version to jailer. (#399) 8 | * Added support for the MMDS configuration. (#290) 9 | * Added PauseVM, ResumeVM, CreateSnapshot and LoadSnapshot capabilities. (#278) (#414) 10 | * Fixed InitrdPath usage. (#295) 11 | 12 | # 0.22.0 13 | * Since firecracker-microvm/firecracker#2125, `cargo build` doesn't build jailer by default. (#263) 14 | * Fix Benchmark Goroutine (#259) 15 | * Jailer configuration API cleanup and improved logging with Debug log level (#255) 16 | * Firecracker is internally has an instance ID, but the SDK didn't have the way to configure the ID. This change connects Config.VMID to the instance ID. (#253) 17 | * Fixed error that was not being test against in `TestWait` (#251) 18 | * Fixes issue where socket path may not be defined since the config file has yet to be loaded (#230) 19 | * Fixed error that was not being test against in `TestNewPlugin` (#225) 20 | * Download Firecracker 0.21.1 and its jailer from Makefile (#218) 21 | 22 | # 0.21.0 23 | * Fixes default jailer socket and seccomp filters to be compatible with firecracker-v0.21.0 (#176) 24 | * Fixes signal handling goroutine leak (#204) 25 | * Machine.Wait now will wait until firecracker has stopped before returning (#182) 26 | * Allowing passing of parsed CNI configs (#177) 27 | 28 | # 0.20.0 29 | * Moves the NetNS field to `Config` from `JailerConfig` (#155). 30 | * Supports forcing CNI network creation (#130). 31 | * Adds `FIRECRACKER_GO_SDK_INIT_TIMEOUT_SECONDS` and `FIRECRACKER_GO_SDK_REQUEST_TIMEOUT_MILLISECONDS` environment variables to configure timeouts (#165). 32 | * Adds `ForwardSignals` to explicitly configure signal handling (#166). 33 | 34 | # 0.19.0 35 | * Firecracker v0.19 API: Vsock API call: PUT /vsocks/{id} changed to PUT /vsock and no longer 36 | appear to support multiple vsock devices. Any subsequent calls to this API 37 | endpoint will override the previous vsock device configuration. 38 | * Firecracker v0.19 API: Removed 'Halting' and 'Halted' instance states. 39 | 40 | # 0.18.0 41 | * Adds support for configuring Network Interfaces via CNI (#126) 42 | * Moves NetworkInterface.HostDevName and NetworkInterface.MacAddress fields to 43 | NetworkInterface.StaticConfiguration.HostDevName and NetworkInterface.StaticConfiguration.MacAddress 44 | fields, respectively. This is a backwards incompatible change, users will need 45 | to update the location of these fields. (#126) 46 | 47 | # 0.17.0 48 | 49 | * Fixes a bug where fifos were not working properly with jailer enabled (#96) 50 | * Fixes bug where context was not being used at all during startVM (#86) 51 | * Updates the jailer's socket path to point to the unix socket in the jailer's workspace (#86) 52 | * Fixes bug where default socketpath would always be used when not using jailer (#84). 53 | * Update for compatibility with Firecracker 0.17.x 54 | * Changes JailerCfg to be a pointer and removes EnableJailer for ease of use (#110). 55 | 56 | # 0.15.1 57 | 58 | * Add the machine.Shutdown() method, enabling access to the SendCtrlAltDel API 59 | added in Firecracker 0.15.0 60 | 61 | # 0.15.0 62 | 63 | * Initial release 64 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /COPYRIGHT_HEADER: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | not use this file except in compliance with the License. A copy of the 5 | License is located at 6 | 7 | http://aws.amazon.com/apache2.0/ 8 | 9 | or in the "license" file accompanying this file. This file is distributed 10 | on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | express or implied. See the License for the specific language governing 12 | permissions and limitations under the License. -------------------------------------------------------------------------------- /HACKING.md: -------------------------------------------------------------------------------- 1 | Developing for this project 2 | ==== 3 | 4 | Testing 5 | --- 6 | 7 | Tests are written using Go's testing framework and can be run with the standard 8 | `go test` tool. If you prefer to use the Makefile, `make test EXTRAGOARGS=-v` 9 | will run tests in verbose mode. By default, the unit tests require root 10 | privileged access. This can be disabled by setting the `DISABLE_ROOT_TESTS` 11 | environment variable. 12 | 13 | You need some external resources in order to run the tests, as described below: 14 | 15 | 1. A firecracker and jailer binary (tested with 0.20.0) must either be 16 | installed as `./testdata/firecracker` or the path must be specified through 17 | the `FC_TEST_BIN` environment variable. The jailer requires go test to be 18 | run with sudo and can also be turned off by setting the `DISABLE_ROOT_TESTS` 19 | env flag. 20 | 2. Access to hardware virtualization via `/dev/kvm` and `/dev/vhost-vsock` 21 | (ensure you have mode `+rw`!) 22 | 3. An uncompressed Linux kernel binary that can boot in Firecracker VM (Must be 23 | installed as `./testdata/vmlinux`) 24 | 4. A tap device owned by your userid (Must be either named `fc-test-tap0` or 25 | have the name specified with the `FC_TEST_TAP` environment variable; try 26 | `sudo ip tuntap add fc-test-tap0 mode tap user $UID` to create `fc-test-tap0` 27 | if you need to create one) 28 | 5. A root filesystem image installed (Must be named `testdata/root-drive.img`) 29 | 6. A secondary device image (Must be named `testdata/drive-2.img`; can be 30 | empty, create it something like 31 | `dd if=/dev/zero of=testdata/drive-2.img bs=1k count=102400`) 32 | 33 | With all of those set up, `make test EXTRAGOARGS=-v` should create a Firecracker 34 | process and run the Linux kernel in a MicroVM. 35 | 36 | There is also a possibility to configure timeouts in firecracker-go-sdk, 37 | you can set those env's to customize tests flow: 38 | ``` 39 | FIRECRACKER_GO_SDK_INIT_TIMEOUT_SECONDS 40 | FIRECRACKER_GO_SDK_REQUEST_TIMEOUT_MILLISECONDS 41 | ``` 42 | You can set them directly or with a help of buildkite, otherwise default values will be used. 43 | 44 | Regenerating the API client 45 | --- 46 | 47 | The API client can be generated using the 48 | [Go swagger implementation](https://goswagger.io/). To do so, perform the 49 | following: 50 | 51 | 1. Update `client/swagger.yaml` 52 | 3. Run `go generate` 53 | 4. Figure out what broke and fix it. 54 | 55 | Continuous Integration 56 | --- 57 | 58 | To access `/dev/kvm`, we are using [BuildKite](https://buildkite.com/) and 59 | Amazon EC2 Bare Metal Instances. 60 | 61 | The instance is pre-configured to have 62 | 63 | - firecracker and jailer under /usr/local/bin. 64 | Both of them are currently v0.20.0. 65 | - vmlinux.bin from 66 | https://s3.amazonaws.com/spec.ccfc.min/img/hello/kernel/hello-vmlinux.bin 67 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Go Firecracker SDK 2 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /balloon.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package firecracker 14 | 15 | import ( 16 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 17 | ) 18 | 19 | // BalloonDevice is a builder that will create a balloon used to set up 20 | // the firecracker microVM. 21 | type BalloonDevice struct { 22 | balloon models.Balloon 23 | } 24 | 25 | type BalloonOpt func(*models.Balloon) 26 | 27 | // NewBalloonDevice will return a new BalloonDevice. 28 | func NewBalloonDevice(amountMib int64, deflateOnOom bool, opts ...BalloonOpt) BalloonDevice { 29 | b := models.Balloon{ 30 | AmountMib: &amountMib, 31 | DeflateOnOom: &deflateOnOom, 32 | } 33 | 34 | for _, opt := range opts { 35 | opt(&b) 36 | } 37 | 38 | return BalloonDevice{balloon: b} 39 | } 40 | 41 | // Build will return a new balloon 42 | func (b BalloonDevice) Build() models.Balloon { 43 | return b.balloon 44 | } 45 | 46 | // WithStatsPollingIntervals is a functional option which sets the time in seconds between refreshing statistics. 47 | func WithStatsPollingIntervals(statsPollingIntervals int64) BalloonOpt { 48 | return func(d *models.Balloon) { 49 | d.StatsPollingIntervals = statsPollingIntervals 50 | } 51 | } 52 | 53 | // UpdateAmountMiB sets the target size of the balloon 54 | func (b BalloonDevice) UpdateAmountMib(amountMib int64) BalloonDevice { 55 | b.balloon.AmountMib = &amountMib 56 | return b 57 | } 58 | 59 | // UpdateStatsPollingIntervals sets the time in seconds between refreshing statistics. 60 | // A non-zero value will enable the statistics. Defaults to 0. 61 | func (b BalloonDevice) UpdateStatsPollingIntervals(statsPollingIntervals int64) BalloonDevice { 62 | b.balloon.StatsPollingIntervals = statsPollingIntervals 63 | return b 64 | } 65 | -------------------------------------------------------------------------------- /balloon_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import ( 17 | "reflect" 18 | "testing" 19 | 20 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 21 | ) 22 | 23 | var ( 24 | expectedAmountMib = int64(6) 25 | expectedDeflateOnOom = true 26 | expectedStatsPollingIntervals = int64(1) 27 | 28 | expectedBalloon = models.Balloon{ 29 | AmountMib: &expectedAmountMib, 30 | DeflateOnOom: &expectedDeflateOnOom, 31 | StatsPollingIntervals: expectedStatsPollingIntervals, 32 | } 33 | ) 34 | 35 | func TestNewBalloonDevice(t *testing.T) { 36 | balloon := NewBalloonDevice(expectedAmountMib, expectedDeflateOnOom, WithStatsPollingIntervals(expectedStatsPollingIntervals)).Build() 37 | if e, a := expectedBalloon, balloon; !reflect.DeepEqual(e, a) { 38 | t.Errorf("expected balloon %v, but received %v", e, a) 39 | } 40 | } 41 | 42 | func TestUpdateAmountMiB(t *testing.T) { 43 | BalloonDevice := NewBalloonDevice(int64(1), expectedDeflateOnOom, WithStatsPollingIntervals(expectedStatsPollingIntervals)) 44 | balloon := BalloonDevice.UpdateAmountMib(expectedAmountMib).Build() 45 | 46 | if e, a := expectedBalloon, balloon; !reflect.DeepEqual(e, a) { 47 | t.Errorf("expected balloon %v, but received %v", e, a) 48 | } 49 | } 50 | 51 | func TestUpdateStatsPollingIntervals(t *testing.T) { 52 | BalloonDevice := NewBalloonDevice(expectedAmountMib, expectedDeflateOnOom) 53 | balloon := BalloonDevice.UpdateStatsPollingIntervals(expectedStatsPollingIntervals).Build() 54 | 55 | if e, a := expectedBalloon, balloon; !reflect.DeepEqual(e, a) { 56 | t.Errorf("expected balloon %v, but received %v", e, a) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /benchmark_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package firecracker 14 | 15 | import ( 16 | "bufio" 17 | "context" 18 | "fmt" 19 | "os" 20 | "path/filepath" 21 | "strings" 22 | "testing" 23 | 24 | "github.com/sirupsen/logrus" 25 | 26 | "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 27 | ) 28 | 29 | const numberOfVMs = 200 30 | 31 | func createMachine(ctx context.Context, name string, forwardSignals []os.Signal) (*Machine, func(), error) { 32 | dir, err := os.MkdirTemp("", name) 33 | if err != nil { 34 | return nil, nil, err 35 | } 36 | cleanup := func() { 37 | os.RemoveAll(dir) 38 | } 39 | 40 | socketPath := filepath.Join(dir, "api.sock") 41 | vmlinuxPath := filepath.Join(testDataPath, "./vmlinux") 42 | logFifo := filepath.Join(dir, "log.fifo") 43 | metrics := filepath.Join(dir, "metrics.fifo") 44 | 45 | config := Config{ 46 | SocketPath: socketPath, 47 | KernelImagePath: vmlinuxPath, 48 | LogFifo: logFifo, 49 | MetricsFifo: metrics, 50 | LogLevel: "Info", 51 | MachineCfg: models.MachineConfiguration{ 52 | VcpuCount: Int64(1), 53 | MemSizeMib: Int64(256), 54 | Smt: Bool(false), 55 | }, 56 | Drives: []models.Drive{ 57 | { 58 | DriveID: String("root"), 59 | IsRootDevice: Bool(true), 60 | IsReadOnly: Bool(true), 61 | PathOnHost: String(testRootfs), 62 | }, 63 | }, 64 | ForwardSignals: forwardSignals, 65 | } 66 | 67 | cmd := VMCommandBuilder{}. 68 | WithSocketPath(socketPath). 69 | WithBin(getFirecrackerBinaryPath()). 70 | Build(ctx) 71 | 72 | log := logrus.New() 73 | log.SetLevel(logrus.FatalLevel) 74 | machine, err := NewMachine(ctx, config, WithProcessRunner(cmd), WithLogger(logrus.NewEntry(log))) 75 | if err != nil { 76 | return nil, cleanup, err 77 | } 78 | 79 | return machine, cleanup, nil 80 | } 81 | 82 | func startAndWaitVM(ctx context.Context, m *Machine) error { 83 | err := m.Start(ctx) 84 | if err != nil { 85 | return err 86 | } 87 | 88 | file, err := os.Open(m.LogFile()) 89 | if err != nil { 90 | return err 91 | } 92 | 93 | scanner := bufio.NewScanner(file) 94 | for scanner.Scan() { 95 | line := scanner.Text() 96 | if strings.Contains(line, "Guest-boot-time") { 97 | break 98 | } 99 | } 100 | err = m.StopVMM() 101 | if err != nil { 102 | return err 103 | } 104 | 105 | err = m.Wait(ctx) 106 | if err != nil { 107 | return err 108 | } 109 | 110 | return nil 111 | } 112 | 113 | func benchmarkForwardSignals(b *testing.B, forwardSignals []os.Signal) { 114 | ctx := context.Background() 115 | 116 | b.Logf("%s: %d", b.Name(), b.N) 117 | 118 | for i := 0; i < b.N; i++ { 119 | errCh := make(chan error, numberOfVMs) 120 | for j := 0; j < numberOfVMs; j++ { 121 | go func() { 122 | var err error 123 | defer func() { errCh <- err }() 124 | 125 | machine, cleanup, err := createMachine(ctx, b.Name(), forwardSignals) 126 | if err != nil { 127 | err = fmt.Errorf("failed to create a VM: %v", err) 128 | return // anonymous defer func() will deliver the error 129 | } 130 | defer cleanup() 131 | 132 | err = startAndWaitVM(ctx, machine) 133 | if err != nil && !strings.Contains(err.Error(), "signal: terminated") { 134 | err = fmt.Errorf("failed to start the VM: %v", err) 135 | return // anonymous defer func() will deliver the error 136 | } 137 | return // anonymous defer func() will deliver this nil error 138 | }() 139 | } 140 | for k := 0; k < numberOfVMs; k++ { 141 | err := <-errCh 142 | if err != nil { 143 | b.Fatal(err) 144 | } 145 | } 146 | close(errCh) 147 | } 148 | } 149 | func BenchmarkForwardSignalsDefault(t *testing.B) { 150 | benchmarkForwardSignals(t, nil) 151 | } 152 | 153 | func BenchmarkForwardSignalsDisable(t *testing.B) { 154 | benchmarkForwardSignals(t, []os.Signal{}) 155 | } 156 | -------------------------------------------------------------------------------- /client/firecracker_client.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package client 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "github.com/go-openapi/runtime" 23 | httptransport "github.com/go-openapi/runtime/client" 24 | 25 | strfmt "github.com/go-openapi/strfmt" 26 | 27 | "github.com/firecracker-microvm/firecracker-go-sdk/client/operations" 28 | ) 29 | 30 | // Default firecracker HTTP client. 31 | var Default = NewHTTPClient(nil) 32 | 33 | const ( 34 | // DefaultHost is the default Host 35 | // found in Meta (info) section of spec file 36 | DefaultHost string = "localhost" 37 | // DefaultBasePath is the default BasePath 38 | // found in Meta (info) section of spec file 39 | DefaultBasePath string = "/" 40 | ) 41 | 42 | // DefaultSchemes are the default schemes found in Meta (info) section of spec file 43 | var DefaultSchemes = []string{"http"} 44 | 45 | // NewHTTPClient creates a new firecracker HTTP client. 46 | func NewHTTPClient(formats strfmt.Registry) *Firecracker { 47 | return NewHTTPClientWithConfig(formats, nil) 48 | } 49 | 50 | // NewHTTPClientWithConfig creates a new firecracker HTTP client, 51 | // using a customizable transport config. 52 | func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *Firecracker { 53 | // ensure nullable parameters have default 54 | if cfg == nil { 55 | cfg = DefaultTransportConfig() 56 | } 57 | 58 | // create transport and client 59 | transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) 60 | return New(transport, formats) 61 | } 62 | 63 | // New creates a new firecracker client 64 | func New(transport runtime.ClientTransport, formats strfmt.Registry) *Firecracker { 65 | // ensure nullable parameters have default 66 | if formats == nil { 67 | formats = strfmt.Default 68 | } 69 | 70 | cli := new(Firecracker) 71 | cli.Transport = transport 72 | 73 | cli.Operations = operations.New(transport, formats) 74 | 75 | return cli 76 | } 77 | 78 | // DefaultTransportConfig creates a TransportConfig with the 79 | // default settings taken from the meta section of the spec file. 80 | func DefaultTransportConfig() *TransportConfig { 81 | return &TransportConfig{ 82 | Host: DefaultHost, 83 | BasePath: DefaultBasePath, 84 | Schemes: DefaultSchemes, 85 | } 86 | } 87 | 88 | // TransportConfig contains the transport related info, 89 | // found in the meta section of the spec file. 90 | type TransportConfig struct { 91 | Host string 92 | BasePath string 93 | Schemes []string 94 | } 95 | 96 | // WithHost overrides the default host, 97 | // provided by the meta section of the spec file. 98 | func (cfg *TransportConfig) WithHost(host string) *TransportConfig { 99 | cfg.Host = host 100 | return cfg 101 | } 102 | 103 | // WithBasePath overrides the default basePath, 104 | // provided by the meta section of the spec file. 105 | func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { 106 | cfg.BasePath = basePath 107 | return cfg 108 | } 109 | 110 | // WithSchemes overrides the default schemes, 111 | // provided by the meta section of the spec file. 112 | func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { 113 | cfg.Schemes = schemes 114 | return cfg 115 | } 116 | 117 | // Firecracker is a client for firecracker 118 | type Firecracker struct { 119 | Operations operations.ClientIface 120 | 121 | Transport runtime.ClientTransport 122 | } 123 | 124 | // SetTransport changes the transport on the client and all its subresources 125 | func (c *Firecracker) SetTransport(transport runtime.ClientTransport) { 126 | c.Transport = transport 127 | 128 | c.Operations = operations.NewClient(transport, nil) 129 | 130 | } 131 | -------------------------------------------------------------------------------- /client/models/balloon.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // Balloon Balloon device descriptor. 30 | // swagger:model Balloon 31 | type Balloon struct { 32 | 33 | // Target balloon size in MiB. 34 | // Required: true 35 | AmountMib *int64 `json:"amount_mib"` 36 | 37 | // Whether the balloon should deflate when the guest has memory pressure. 38 | // Required: true 39 | DeflateOnOom *bool `json:"deflate_on_oom"` 40 | 41 | // Interval in seconds between refreshing statistics. A non-zero value will enable the statistics. Defaults to 0. 42 | StatsPollingIntervals int64 `json:"stats_polling_interval_s,omitempty"` 43 | } 44 | 45 | // Validate validates this balloon 46 | func (m *Balloon) Validate(formats strfmt.Registry) error { 47 | var res []error 48 | 49 | if err := m.validateAmountMib(formats); err != nil { 50 | res = append(res, err) 51 | } 52 | 53 | if err := m.validateDeflateOnOom(formats); err != nil { 54 | res = append(res, err) 55 | } 56 | 57 | if len(res) > 0 { 58 | return errors.CompositeValidationError(res...) 59 | } 60 | return nil 61 | } 62 | 63 | func (m *Balloon) validateAmountMib(formats strfmt.Registry) error { 64 | 65 | if err := validate.Required("amount_mib", "body", m.AmountMib); err != nil { 66 | return err 67 | } 68 | 69 | return nil 70 | } 71 | 72 | func (m *Balloon) validateDeflateOnOom(formats strfmt.Registry) error { 73 | 74 | if err := validate.Required("deflate_on_oom", "body", m.DeflateOnOom); err != nil { 75 | return err 76 | } 77 | 78 | return nil 79 | } 80 | 81 | // MarshalBinary interface implementation 82 | func (m *Balloon) MarshalBinary() ([]byte, error) { 83 | if m == nil { 84 | return nil, nil 85 | } 86 | return swag.WriteJSON(m) 87 | } 88 | 89 | // UnmarshalBinary interface implementation 90 | func (m *Balloon) UnmarshalBinary(b []byte) error { 91 | var res Balloon 92 | if err := swag.ReadJSON(b, &res); err != nil { 93 | return err 94 | } 95 | *m = res 96 | return nil 97 | } 98 | -------------------------------------------------------------------------------- /client/models/balloon_stats_update.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // BalloonStatsUpdate Update the statistics polling interval, with the first statistics update scheduled immediately. Statistics cannot be turned on/off after boot. 30 | // swagger:model BalloonStatsUpdate 31 | type BalloonStatsUpdate struct { 32 | 33 | // Interval in seconds between refreshing statistics. 34 | // Required: true 35 | StatsPollingIntervals *int64 `json:"stats_polling_interval_s"` 36 | } 37 | 38 | // Validate validates this balloon stats update 39 | func (m *BalloonStatsUpdate) Validate(formats strfmt.Registry) error { 40 | var res []error 41 | 42 | if err := m.validateStatsPollingIntervals(formats); err != nil { 43 | res = append(res, err) 44 | } 45 | 46 | if len(res) > 0 { 47 | return errors.CompositeValidationError(res...) 48 | } 49 | return nil 50 | } 51 | 52 | func (m *BalloonStatsUpdate) validateStatsPollingIntervals(formats strfmt.Registry) error { 53 | 54 | if err := validate.Required("stats_polling_interval_s", "body", m.StatsPollingIntervals); err != nil { 55 | return err 56 | } 57 | 58 | return nil 59 | } 60 | 61 | // MarshalBinary interface implementation 62 | func (m *BalloonStatsUpdate) MarshalBinary() ([]byte, error) { 63 | if m == nil { 64 | return nil, nil 65 | } 66 | return swag.WriteJSON(m) 67 | } 68 | 69 | // UnmarshalBinary interface implementation 70 | func (m *BalloonStatsUpdate) UnmarshalBinary(b []byte) error { 71 | var res BalloonStatsUpdate 72 | if err := swag.ReadJSON(b, &res); err != nil { 73 | return err 74 | } 75 | *m = res 76 | return nil 77 | } 78 | -------------------------------------------------------------------------------- /client/models/balloon_update.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // BalloonUpdate Balloon device descriptor. 30 | // swagger:model BalloonUpdate 31 | type BalloonUpdate struct { 32 | 33 | // Target balloon size in MiB. 34 | // Required: true 35 | AmountMib *int64 `json:"amount_mib"` 36 | } 37 | 38 | // Validate validates this balloon update 39 | func (m *BalloonUpdate) Validate(formats strfmt.Registry) error { 40 | var res []error 41 | 42 | if err := m.validateAmountMib(formats); err != nil { 43 | res = append(res, err) 44 | } 45 | 46 | if len(res) > 0 { 47 | return errors.CompositeValidationError(res...) 48 | } 49 | return nil 50 | } 51 | 52 | func (m *BalloonUpdate) validateAmountMib(formats strfmt.Registry) error { 53 | 54 | if err := validate.Required("amount_mib", "body", m.AmountMib); err != nil { 55 | return err 56 | } 57 | 58 | return nil 59 | } 60 | 61 | // MarshalBinary interface implementation 62 | func (m *BalloonUpdate) MarshalBinary() ([]byte, error) { 63 | if m == nil { 64 | return nil, nil 65 | } 66 | return swag.WriteJSON(m) 67 | } 68 | 69 | // UnmarshalBinary interface implementation 70 | func (m *BalloonUpdate) UnmarshalBinary(b []byte) error { 71 | var res BalloonUpdate 72 | if err := swag.ReadJSON(b, &res); err != nil { 73 | return err 74 | } 75 | *m = res 76 | return nil 77 | } 78 | -------------------------------------------------------------------------------- /client/models/boot_source.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // BootSource Boot source descriptor. 30 | // swagger:model BootSource 31 | type BootSource struct { 32 | 33 | // Kernel boot arguments 34 | BootArgs string `json:"boot_args,omitempty"` 35 | 36 | // Host level path to the initrd image used to boot the guest 37 | InitrdPath string `json:"initrd_path,omitempty"` 38 | 39 | // Host level path to the kernel image used to boot the guest 40 | // Required: true 41 | KernelImagePath *string `json:"kernel_image_path"` 42 | } 43 | 44 | // Validate validates this boot source 45 | func (m *BootSource) Validate(formats strfmt.Registry) error { 46 | var res []error 47 | 48 | if err := m.validateKernelImagePath(formats); err != nil { 49 | res = append(res, err) 50 | } 51 | 52 | if len(res) > 0 { 53 | return errors.CompositeValidationError(res...) 54 | } 55 | return nil 56 | } 57 | 58 | func (m *BootSource) validateKernelImagePath(formats strfmt.Registry) error { 59 | 60 | if err := validate.Required("kernel_image_path", "body", m.KernelImagePath); err != nil { 61 | return err 62 | } 63 | 64 | return nil 65 | } 66 | 67 | // MarshalBinary interface implementation 68 | func (m *BootSource) MarshalBinary() ([]byte, error) { 69 | if m == nil { 70 | return nil, nil 71 | } 72 | return swag.WriteJSON(m) 73 | } 74 | 75 | // UnmarshalBinary interface implementation 76 | func (m *BootSource) UnmarshalBinary(b []byte) error { 77 | var res BootSource 78 | if err := swag.ReadJSON(b, &res); err != nil { 79 | return err 80 | } 81 | *m = res 82 | return nil 83 | } 84 | -------------------------------------------------------------------------------- /client/models/cpu_config.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | ) 26 | 27 | // CPUConfig The CPU configuration template defines a set of bit maps as modifiers of flags accessed by register to be disabled/enabled for the microvm. 28 | // swagger:model CpuConfig 29 | type CPUConfig string 30 | 31 | // Validate validates this Cpu config 32 | func (m CPUConfig) Validate(formats strfmt.Registry) error { 33 | var res []error 34 | 35 | if len(res) > 0 { 36 | return errors.CompositeValidationError(res...) 37 | } 38 | return nil 39 | } 40 | -------------------------------------------------------------------------------- /client/models/cpu_template.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "encoding/json" 23 | 24 | strfmt "github.com/go-openapi/strfmt" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/validate" 28 | ) 29 | 30 | // CPUTemplate The CPU Template defines a set of flags to be disabled from the microvm so that the features exposed to the guest are the same as in the selected instance type. 31 | // swagger:model CpuTemplate 32 | type CPUTemplate string 33 | 34 | const ( 35 | 36 | // CPUTemplateC3 captures enum value "C3" 37 | CPUTemplateC3 CPUTemplate = "C3" 38 | 39 | // CPUTemplateT2 captures enum value "T2" 40 | CPUTemplateT2 CPUTemplate = "T2" 41 | 42 | // CPUTemplateT2S captures enum value "T2S" 43 | CPUTemplateT2S CPUTemplate = "T2S" 44 | 45 | // CPUTemplateT2CL captures enum value "T2CL" 46 | CPUTemplateT2CL CPUTemplate = "T2CL" 47 | 48 | // CPUTemplateT2A captures enum value "T2A" 49 | CPUTemplateT2A CPUTemplate = "T2A" 50 | 51 | // CPUTemplateV1N1 captures enum value "V1N1" 52 | CPUTemplateV1N1 CPUTemplate = "V1N1" 53 | 54 | // CPUTemplateNone captures enum value "None" 55 | CPUTemplateNone CPUTemplate = "None" 56 | ) 57 | 58 | // for schema 59 | var cpuTemplateEnum []interface{} 60 | 61 | func init() { 62 | var res []CPUTemplate 63 | if err := json.Unmarshal([]byte(`["C3","T2","T2S","T2CL","T2A","V1N1","None"]`), &res); err != nil { 64 | panic(err) 65 | } 66 | for _, v := range res { 67 | cpuTemplateEnum = append(cpuTemplateEnum, v) 68 | } 69 | } 70 | 71 | func (m CPUTemplate) validateCPUTemplateEnum(path, location string, value CPUTemplate) error { 72 | if err := validate.Enum(path, location, value, cpuTemplateEnum); err != nil { 73 | return err 74 | } 75 | return nil 76 | } 77 | 78 | // Validate validates this Cpu template 79 | func (m CPUTemplate) Validate(formats strfmt.Registry) error { 80 | var res []error 81 | 82 | // value enum 83 | if err := m.validateCPUTemplateEnum("", "body", m); err != nil { 84 | return err 85 | } 86 | 87 | if len(res) > 0 { 88 | return errors.CompositeValidationError(res...) 89 | } 90 | return nil 91 | } 92 | -------------------------------------------------------------------------------- /client/models/entropy_device.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | ) 27 | 28 | // EntropyDevice Defines an entropy device. 29 | // swagger:model EntropyDevice 30 | type EntropyDevice struct { 31 | 32 | // rate limiter 33 | RateLimiter *RateLimiter `json:"rate_limiter,omitempty"` 34 | } 35 | 36 | // Validate validates this entropy device 37 | func (m *EntropyDevice) Validate(formats strfmt.Registry) error { 38 | var res []error 39 | 40 | if err := m.validateRateLimiter(formats); err != nil { 41 | res = append(res, err) 42 | } 43 | 44 | if len(res) > 0 { 45 | return errors.CompositeValidationError(res...) 46 | } 47 | return nil 48 | } 49 | 50 | func (m *EntropyDevice) validateRateLimiter(formats strfmt.Registry) error { 51 | 52 | if swag.IsZero(m.RateLimiter) { // not required 53 | return nil 54 | } 55 | 56 | if m.RateLimiter != nil { 57 | if err := m.RateLimiter.Validate(formats); err != nil { 58 | if ve, ok := err.(*errors.Validation); ok { 59 | return ve.ValidateName("rate_limiter") 60 | } 61 | return err 62 | } 63 | } 64 | 65 | return nil 66 | } 67 | 68 | // MarshalBinary interface implementation 69 | func (m *EntropyDevice) MarshalBinary() ([]byte, error) { 70 | if m == nil { 71 | return nil, nil 72 | } 73 | return swag.WriteJSON(m) 74 | } 75 | 76 | // UnmarshalBinary interface implementation 77 | func (m *EntropyDevice) UnmarshalBinary(b []byte) error { 78 | var res EntropyDevice 79 | if err := swag.ReadJSON(b, &res); err != nil { 80 | return err 81 | } 82 | *m = res 83 | return nil 84 | } 85 | -------------------------------------------------------------------------------- /client/models/error.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/swag" 25 | ) 26 | 27 | // Error error 28 | // swagger:model Error 29 | type Error struct { 30 | 31 | // A description of the error condition 32 | // Read Only: true 33 | FaultMessage string `json:"fault_message,omitempty"` 34 | } 35 | 36 | // Validate validates this error 37 | func (m *Error) Validate(formats strfmt.Registry) error { 38 | return nil 39 | } 40 | 41 | // MarshalBinary interface implementation 42 | func (m *Error) MarshalBinary() ([]byte, error) { 43 | if m == nil { 44 | return nil, nil 45 | } 46 | return swag.WriteJSON(m) 47 | } 48 | 49 | // UnmarshalBinary interface implementation 50 | func (m *Error) UnmarshalBinary(b []byte) error { 51 | var res Error 52 | if err := swag.ReadJSON(b, &res); err != nil { 53 | return err 54 | } 55 | *m = res 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /client/models/firecracker_version.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // FirecrackerVersion Describes the Firecracker version. 30 | // swagger:model FirecrackerVersion 31 | type FirecrackerVersion struct { 32 | 33 | // Firecracker build version. 34 | // Required: true 35 | FirecrackerVersion *string `json:"firecracker_version"` 36 | } 37 | 38 | // Validate validates this firecracker version 39 | func (m *FirecrackerVersion) Validate(formats strfmt.Registry) error { 40 | var res []error 41 | 42 | if err := m.validateFirecrackerVersion(formats); err != nil { 43 | res = append(res, err) 44 | } 45 | 46 | if len(res) > 0 { 47 | return errors.CompositeValidationError(res...) 48 | } 49 | return nil 50 | } 51 | 52 | func (m *FirecrackerVersion) validateFirecrackerVersion(formats strfmt.Registry) error { 53 | 54 | if err := validate.Required("firecracker_version", "body", m.FirecrackerVersion); err != nil { 55 | return err 56 | } 57 | 58 | return nil 59 | } 60 | 61 | // MarshalBinary interface implementation 62 | func (m *FirecrackerVersion) MarshalBinary() ([]byte, error) { 63 | if m == nil { 64 | return nil, nil 65 | } 66 | return swag.WriteJSON(m) 67 | } 68 | 69 | // UnmarshalBinary interface implementation 70 | func (m *FirecrackerVersion) UnmarshalBinary(b []byte) error { 71 | var res FirecrackerVersion 72 | if err := swag.ReadJSON(b, &res); err != nil { 73 | return err 74 | } 75 | *m = res 76 | return nil 77 | } 78 | -------------------------------------------------------------------------------- /client/models/instance_action_info.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "encoding/json" 23 | 24 | strfmt "github.com/go-openapi/strfmt" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/swag" 28 | "github.com/go-openapi/validate" 29 | ) 30 | 31 | // InstanceActionInfo Variant wrapper containing the real action. 32 | // swagger:model InstanceActionInfo 33 | type InstanceActionInfo struct { 34 | 35 | // Enumeration indicating what type of action is contained in the payload 36 | // Required: true 37 | // Enum: [FlushMetrics InstanceStart SendCtrlAltDel] 38 | ActionType *string `json:"action_type"` 39 | } 40 | 41 | // Validate validates this instance action info 42 | func (m *InstanceActionInfo) Validate(formats strfmt.Registry) error { 43 | var res []error 44 | 45 | if err := m.validateActionType(formats); err != nil { 46 | res = append(res, err) 47 | } 48 | 49 | if len(res) > 0 { 50 | return errors.CompositeValidationError(res...) 51 | } 52 | return nil 53 | } 54 | 55 | var instanceActionInfoTypeActionTypePropEnum []interface{} 56 | 57 | func init() { 58 | var res []string 59 | if err := json.Unmarshal([]byte(`["FlushMetrics","InstanceStart","SendCtrlAltDel"]`), &res); err != nil { 60 | panic(err) 61 | } 62 | for _, v := range res { 63 | instanceActionInfoTypeActionTypePropEnum = append(instanceActionInfoTypeActionTypePropEnum, v) 64 | } 65 | } 66 | 67 | const ( 68 | 69 | // InstanceActionInfoActionTypeFlushMetrics captures enum value "FlushMetrics" 70 | InstanceActionInfoActionTypeFlushMetrics string = "FlushMetrics" 71 | 72 | // InstanceActionInfoActionTypeInstanceStart captures enum value "InstanceStart" 73 | InstanceActionInfoActionTypeInstanceStart string = "InstanceStart" 74 | 75 | // InstanceActionInfoActionTypeSendCtrlAltDel captures enum value "SendCtrlAltDel" 76 | InstanceActionInfoActionTypeSendCtrlAltDel string = "SendCtrlAltDel" 77 | ) 78 | 79 | // prop value enum 80 | func (m *InstanceActionInfo) validateActionTypeEnum(path, location string, value string) error { 81 | if err := validate.Enum(path, location, value, instanceActionInfoTypeActionTypePropEnum); err != nil { 82 | return err 83 | } 84 | return nil 85 | } 86 | 87 | func (m *InstanceActionInfo) validateActionType(formats strfmt.Registry) error { 88 | 89 | if err := validate.Required("action_type", "body", m.ActionType); err != nil { 90 | return err 91 | } 92 | 93 | // value enum 94 | if err := m.validateActionTypeEnum("action_type", "body", *m.ActionType); err != nil { 95 | return err 96 | } 97 | 98 | return nil 99 | } 100 | 101 | // MarshalBinary interface implementation 102 | func (m *InstanceActionInfo) MarshalBinary() ([]byte, error) { 103 | if m == nil { 104 | return nil, nil 105 | } 106 | return swag.WriteJSON(m) 107 | } 108 | 109 | // UnmarshalBinary interface implementation 110 | func (m *InstanceActionInfo) UnmarshalBinary(b []byte) error { 111 | var res InstanceActionInfo 112 | if err := swag.ReadJSON(b, &res); err != nil { 113 | return err 114 | } 115 | *m = res 116 | return nil 117 | } 118 | -------------------------------------------------------------------------------- /client/models/logger.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "encoding/json" 23 | 24 | strfmt "github.com/go-openapi/strfmt" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/swag" 28 | "github.com/go-openapi/validate" 29 | ) 30 | 31 | // Logger Describes the configuration option for the logging capability. 32 | // swagger:model Logger 33 | type Logger struct { 34 | 35 | // Set the level. The possible values are case-insensitive. 36 | // Enum: [Error Warning Info Debug] 37 | Level *string `json:"level,omitempty"` 38 | 39 | // Path to the named pipe or file for the human readable log output. 40 | // Required: true 41 | LogPath *string `json:"log_path"` 42 | 43 | // Whether or not to output the level in the logs. 44 | ShowLevel *bool `json:"show_level,omitempty"` 45 | 46 | // Whether or not to include the file path and line number of the log's origin. 47 | ShowLogOrigin *bool `json:"show_log_origin,omitempty"` 48 | } 49 | 50 | // Validate validates this logger 51 | func (m *Logger) Validate(formats strfmt.Registry) error { 52 | var res []error 53 | 54 | if err := m.validateLevel(formats); err != nil { 55 | res = append(res, err) 56 | } 57 | 58 | if err := m.validateLogPath(formats); err != nil { 59 | res = append(res, err) 60 | } 61 | 62 | if len(res) > 0 { 63 | return errors.CompositeValidationError(res...) 64 | } 65 | return nil 66 | } 67 | 68 | var loggerTypeLevelPropEnum []interface{} 69 | 70 | func init() { 71 | var res []string 72 | if err := json.Unmarshal([]byte(`["Error","Warning","Info","Debug"]`), &res); err != nil { 73 | panic(err) 74 | } 75 | for _, v := range res { 76 | loggerTypeLevelPropEnum = append(loggerTypeLevelPropEnum, v) 77 | } 78 | } 79 | 80 | const ( 81 | 82 | // LoggerLevelError captures enum value "Error" 83 | LoggerLevelError string = "Error" 84 | 85 | // LoggerLevelWarning captures enum value "Warning" 86 | LoggerLevelWarning string = "Warning" 87 | 88 | // LoggerLevelInfo captures enum value "Info" 89 | LoggerLevelInfo string = "Info" 90 | 91 | // LoggerLevelDebug captures enum value "Debug" 92 | LoggerLevelDebug string = "Debug" 93 | ) 94 | 95 | // prop value enum 96 | func (m *Logger) validateLevelEnum(path, location string, value string) error { 97 | if err := validate.Enum(path, location, value, loggerTypeLevelPropEnum); err != nil { 98 | return err 99 | } 100 | return nil 101 | } 102 | 103 | func (m *Logger) validateLevel(formats strfmt.Registry) error { 104 | 105 | if swag.IsZero(m.Level) { // not required 106 | return nil 107 | } 108 | 109 | // value enum 110 | if err := m.validateLevelEnum("level", "body", *m.Level); err != nil { 111 | return err 112 | } 113 | 114 | return nil 115 | } 116 | 117 | func (m *Logger) validateLogPath(formats strfmt.Registry) error { 118 | 119 | if err := validate.Required("log_path", "body", m.LogPath); err != nil { 120 | return err 121 | } 122 | 123 | return nil 124 | } 125 | 126 | // MarshalBinary interface implementation 127 | func (m *Logger) MarshalBinary() ([]byte, error) { 128 | if m == nil { 129 | return nil, nil 130 | } 131 | return swag.WriteJSON(m) 132 | } 133 | 134 | // UnmarshalBinary interface implementation 135 | func (m *Logger) UnmarshalBinary(b []byte) error { 136 | var res Logger 137 | if err := swag.ReadJSON(b, &res); err != nil { 138 | return err 139 | } 140 | *m = res 141 | return nil 142 | } 143 | -------------------------------------------------------------------------------- /client/models/machine_configuration.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // MachineConfiguration Describes the number of vCPUs, memory size, SMT capabilities and the CPU template. 30 | // swagger:model MachineConfiguration 31 | type MachineConfiguration struct { 32 | 33 | // cpu template 34 | CPUTemplate CPUTemplate `json:"cpu_template,omitempty"` 35 | 36 | // Memory size of VM 37 | // Required: true 38 | MemSizeMib *int64 `json:"mem_size_mib"` 39 | 40 | // Flag for enabling/disabling simultaneous multithreading. Can be enabled only on x86. 41 | Smt *bool `json:"smt,omitempty"` 42 | 43 | // Enable dirty page tracking. If this is enabled, then incremental guest memory snapshots can be created. These belong to diff snapshots, which contain, besides the microVM state, only the memory dirtied since a previous snapshot. Full snapshots each contain a full copy of the guest memory. 44 | TrackDirtyPages *bool `json:"track_dirty_pages,omitempty"` 45 | 46 | // Number of vCPUs (either 1 or an even number) 47 | // Required: true 48 | // Maximum: 32 49 | // Minimum: 1 50 | VcpuCount *int64 `json:"vcpu_count"` 51 | } 52 | 53 | // Validate validates this machine configuration 54 | func (m *MachineConfiguration) Validate(formats strfmt.Registry) error { 55 | var res []error 56 | 57 | if err := m.validateCPUTemplate(formats); err != nil { 58 | res = append(res, err) 59 | } 60 | 61 | if err := m.validateMemSizeMib(formats); err != nil { 62 | res = append(res, err) 63 | } 64 | 65 | if err := m.validateVcpuCount(formats); err != nil { 66 | res = append(res, err) 67 | } 68 | 69 | if len(res) > 0 { 70 | return errors.CompositeValidationError(res...) 71 | } 72 | return nil 73 | } 74 | 75 | func (m *MachineConfiguration) validateCPUTemplate(formats strfmt.Registry) error { 76 | 77 | if swag.IsZero(m.CPUTemplate) { // not required 78 | return nil 79 | } 80 | 81 | if err := m.CPUTemplate.Validate(formats); err != nil { 82 | if ve, ok := err.(*errors.Validation); ok { 83 | return ve.ValidateName("cpu_template") 84 | } 85 | return err 86 | } 87 | 88 | return nil 89 | } 90 | 91 | func (m *MachineConfiguration) validateMemSizeMib(formats strfmt.Registry) error { 92 | 93 | if err := validate.Required("mem_size_mib", "body", m.MemSizeMib); err != nil { 94 | return err 95 | } 96 | 97 | return nil 98 | } 99 | 100 | func (m *MachineConfiguration) validateVcpuCount(formats strfmt.Registry) error { 101 | 102 | if err := validate.Required("vcpu_count", "body", m.VcpuCount); err != nil { 103 | return err 104 | } 105 | 106 | if err := validate.MinimumInt("vcpu_count", "body", int64(*m.VcpuCount), 1, false); err != nil { 107 | return err 108 | } 109 | 110 | if err := validate.MaximumInt("vcpu_count", "body", int64(*m.VcpuCount), 32, false); err != nil { 111 | return err 112 | } 113 | 114 | return nil 115 | } 116 | 117 | // MarshalBinary interface implementation 118 | func (m *MachineConfiguration) MarshalBinary() ([]byte, error) { 119 | if m == nil { 120 | return nil, nil 121 | } 122 | return swag.WriteJSON(m) 123 | } 124 | 125 | // UnmarshalBinary interface implementation 126 | func (m *MachineConfiguration) UnmarshalBinary(b []byte) error { 127 | var res MachineConfiguration 128 | if err := swag.ReadJSON(b, &res); err != nil { 129 | return err 130 | } 131 | *m = res 132 | return nil 133 | } 134 | -------------------------------------------------------------------------------- /client/models/memory_backend.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "encoding/json" 23 | 24 | strfmt "github.com/go-openapi/strfmt" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/swag" 28 | "github.com/go-openapi/validate" 29 | ) 30 | 31 | // MemoryBackend memory backend 32 | // swagger:model MemoryBackend 33 | type MemoryBackend struct { 34 | 35 | // Based on 'backend_type' it is either 1) Path to the file that contains the guest memory to be loaded 2) Path to the UDS where a process is listening for a UFFD initialization control payload and open file descriptor that it can use to serve this process's guest memory page faults 36 | // Required: true 37 | BackendPath *string `json:"backend_path"` 38 | 39 | // backend type 40 | // Required: true 41 | // Enum: [File Uffd] 42 | BackendType *string `json:"backend_type"` 43 | } 44 | 45 | // Validate validates this memory backend 46 | func (m *MemoryBackend) Validate(formats strfmt.Registry) error { 47 | var res []error 48 | 49 | if err := m.validateBackendPath(formats); err != nil { 50 | res = append(res, err) 51 | } 52 | 53 | if err := m.validateBackendType(formats); err != nil { 54 | res = append(res, err) 55 | } 56 | 57 | if len(res) > 0 { 58 | return errors.CompositeValidationError(res...) 59 | } 60 | return nil 61 | } 62 | 63 | func (m *MemoryBackend) validateBackendPath(formats strfmt.Registry) error { 64 | 65 | if err := validate.Required("backend_path", "body", m.BackendPath); err != nil { 66 | return err 67 | } 68 | 69 | return nil 70 | } 71 | 72 | var memoryBackendTypeBackendTypePropEnum []interface{} 73 | 74 | func init() { 75 | var res []string 76 | if err := json.Unmarshal([]byte(`["File","Uffd"]`), &res); err != nil { 77 | panic(err) 78 | } 79 | for _, v := range res { 80 | memoryBackendTypeBackendTypePropEnum = append(memoryBackendTypeBackendTypePropEnum, v) 81 | } 82 | } 83 | 84 | const ( 85 | 86 | // MemoryBackendBackendTypeFile captures enum value "File" 87 | MemoryBackendBackendTypeFile string = "File" 88 | 89 | // MemoryBackendBackendTypeUffd captures enum value "Uffd" 90 | MemoryBackendBackendTypeUffd string = "Uffd" 91 | ) 92 | 93 | // prop value enum 94 | func (m *MemoryBackend) validateBackendTypeEnum(path, location string, value string) error { 95 | if err := validate.Enum(path, location, value, memoryBackendTypeBackendTypePropEnum); err != nil { 96 | return err 97 | } 98 | return nil 99 | } 100 | 101 | func (m *MemoryBackend) validateBackendType(formats strfmt.Registry) error { 102 | 103 | if err := validate.Required("backend_type", "body", m.BackendType); err != nil { 104 | return err 105 | } 106 | 107 | // value enum 108 | if err := m.validateBackendTypeEnum("backend_type", "body", *m.BackendType); err != nil { 109 | return err 110 | } 111 | 112 | return nil 113 | } 114 | 115 | // MarshalBinary interface implementation 116 | func (m *MemoryBackend) MarshalBinary() ([]byte, error) { 117 | if m == nil { 118 | return nil, nil 119 | } 120 | return swag.WriteJSON(m) 121 | } 122 | 123 | // UnmarshalBinary interface implementation 124 | func (m *MemoryBackend) UnmarshalBinary(b []byte) error { 125 | var res MemoryBackend 126 | if err := swag.ReadJSON(b, &res); err != nil { 127 | return err 128 | } 129 | *m = res 130 | return nil 131 | } 132 | -------------------------------------------------------------------------------- /client/models/metrics.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // Metrics Describes the configuration option for the metrics capability. 30 | // swagger:model Metrics 31 | type Metrics struct { 32 | 33 | // Path to the named pipe or file where the JSON-formatted metrics are flushed. 34 | // Required: true 35 | MetricsPath *string `json:"metrics_path"` 36 | } 37 | 38 | // Validate validates this metrics 39 | func (m *Metrics) Validate(formats strfmt.Registry) error { 40 | var res []error 41 | 42 | if err := m.validateMetricsPath(formats); err != nil { 43 | res = append(res, err) 44 | } 45 | 46 | if len(res) > 0 { 47 | return errors.CompositeValidationError(res...) 48 | } 49 | return nil 50 | } 51 | 52 | func (m *Metrics) validateMetricsPath(formats strfmt.Registry) error { 53 | 54 | if err := validate.Required("metrics_path", "body", m.MetricsPath); err != nil { 55 | return err 56 | } 57 | 58 | return nil 59 | } 60 | 61 | // MarshalBinary interface implementation 62 | func (m *Metrics) MarshalBinary() ([]byte, error) { 63 | if m == nil { 64 | return nil, nil 65 | } 66 | return swag.WriteJSON(m) 67 | } 68 | 69 | // UnmarshalBinary interface implementation 70 | func (m *Metrics) UnmarshalBinary(b []byte) error { 71 | var res Metrics 72 | if err := swag.ReadJSON(b, &res); err != nil { 73 | return err 74 | } 75 | *m = res 76 | return nil 77 | } 78 | -------------------------------------------------------------------------------- /client/models/mmds_config.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "encoding/json" 23 | 24 | strfmt "github.com/go-openapi/strfmt" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/swag" 28 | "github.com/go-openapi/validate" 29 | ) 30 | 31 | // MmdsConfig Defines the MMDS configuration. 32 | // swagger:model MmdsConfig 33 | type MmdsConfig struct { 34 | 35 | // A valid IPv4 link-local address. 36 | IPV4Address *string `json:"ipv4_address,omitempty"` 37 | 38 | // List of the network interface IDs capable of forwarding packets to the MMDS. Network interface IDs mentioned must be valid at the time of this request. The net device model will reply to HTTP GET requests sent to the MMDS address via the interfaces mentioned. In this case, both ARP requests and TCP segments heading to `ipv4_address` are intercepted by the device model, and do not reach the associated TAP device. 39 | // Required: true 40 | NetworkInterfaces []string `json:"network_interfaces"` 41 | 42 | // Enumeration indicating the MMDS version to be configured. 43 | // Enum: [V1 V2] 44 | Version *string `json:"version,omitempty"` 45 | } 46 | 47 | // Validate validates this mmds config 48 | func (m *MmdsConfig) Validate(formats strfmt.Registry) error { 49 | var res []error 50 | 51 | if err := m.validateNetworkInterfaces(formats); err != nil { 52 | res = append(res, err) 53 | } 54 | 55 | if err := m.validateVersion(formats); err != nil { 56 | res = append(res, err) 57 | } 58 | 59 | if len(res) > 0 { 60 | return errors.CompositeValidationError(res...) 61 | } 62 | return nil 63 | } 64 | 65 | func (m *MmdsConfig) validateNetworkInterfaces(formats strfmt.Registry) error { 66 | 67 | if err := validate.Required("network_interfaces", "body", m.NetworkInterfaces); err != nil { 68 | return err 69 | } 70 | 71 | return nil 72 | } 73 | 74 | var mmdsConfigTypeVersionPropEnum []interface{} 75 | 76 | func init() { 77 | var res []string 78 | if err := json.Unmarshal([]byte(`["V1","V2"]`), &res); err != nil { 79 | panic(err) 80 | } 81 | for _, v := range res { 82 | mmdsConfigTypeVersionPropEnum = append(mmdsConfigTypeVersionPropEnum, v) 83 | } 84 | } 85 | 86 | const ( 87 | 88 | // MmdsConfigVersionV1 captures enum value "V1" 89 | MmdsConfigVersionV1 string = "V1" 90 | 91 | // MmdsConfigVersionV2 captures enum value "V2" 92 | MmdsConfigVersionV2 string = "V2" 93 | ) 94 | 95 | // prop value enum 96 | func (m *MmdsConfig) validateVersionEnum(path, location string, value string) error { 97 | if err := validate.Enum(path, location, value, mmdsConfigTypeVersionPropEnum); err != nil { 98 | return err 99 | } 100 | return nil 101 | } 102 | 103 | func (m *MmdsConfig) validateVersion(formats strfmt.Registry) error { 104 | 105 | if swag.IsZero(m.Version) { // not required 106 | return nil 107 | } 108 | 109 | // value enum 110 | if err := m.validateVersionEnum("version", "body", *m.Version); err != nil { 111 | return err 112 | } 113 | 114 | return nil 115 | } 116 | 117 | // MarshalBinary interface implementation 118 | func (m *MmdsConfig) MarshalBinary() ([]byte, error) { 119 | if m == nil { 120 | return nil, nil 121 | } 122 | return swag.WriteJSON(m) 123 | } 124 | 125 | // UnmarshalBinary interface implementation 126 | func (m *MmdsConfig) UnmarshalBinary(b []byte) error { 127 | var res MmdsConfig 128 | if err := swag.ReadJSON(b, &res); err != nil { 129 | return err 130 | } 131 | *m = res 132 | return nil 133 | } 134 | -------------------------------------------------------------------------------- /client/models/mmds_contents_object.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | // MmdsContentsObject Describes the contents of MMDS in JSON format. 22 | // swagger:model MmdsContentsObject 23 | type MmdsContentsObject interface{} 24 | -------------------------------------------------------------------------------- /client/models/network_interface.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // NetworkInterface Defines a network interface. 30 | // swagger:model NetworkInterface 31 | type NetworkInterface struct { 32 | 33 | // guest mac 34 | GuestMac string `json:"guest_mac,omitempty"` 35 | 36 | // Host level path for the guest network interface 37 | // Required: true 38 | HostDevName *string `json:"host_dev_name"` 39 | 40 | // iface id 41 | // Required: true 42 | IfaceID *string `json:"iface_id"` 43 | 44 | // rx rate limiter 45 | RxRateLimiter *RateLimiter `json:"rx_rate_limiter,omitempty"` 46 | 47 | // tx rate limiter 48 | TxRateLimiter *RateLimiter `json:"tx_rate_limiter,omitempty"` 49 | } 50 | 51 | // Validate validates this network interface 52 | func (m *NetworkInterface) Validate(formats strfmt.Registry) error { 53 | var res []error 54 | 55 | if err := m.validateHostDevName(formats); err != nil { 56 | res = append(res, err) 57 | } 58 | 59 | if err := m.validateIfaceID(formats); err != nil { 60 | res = append(res, err) 61 | } 62 | 63 | if err := m.validateRxRateLimiter(formats); err != nil { 64 | res = append(res, err) 65 | } 66 | 67 | if err := m.validateTxRateLimiter(formats); err != nil { 68 | res = append(res, err) 69 | } 70 | 71 | if len(res) > 0 { 72 | return errors.CompositeValidationError(res...) 73 | } 74 | return nil 75 | } 76 | 77 | func (m *NetworkInterface) validateHostDevName(formats strfmt.Registry) error { 78 | 79 | if err := validate.Required("host_dev_name", "body", m.HostDevName); err != nil { 80 | return err 81 | } 82 | 83 | return nil 84 | } 85 | 86 | func (m *NetworkInterface) validateIfaceID(formats strfmt.Registry) error { 87 | 88 | if err := validate.Required("iface_id", "body", m.IfaceID); err != nil { 89 | return err 90 | } 91 | 92 | return nil 93 | } 94 | 95 | func (m *NetworkInterface) validateRxRateLimiter(formats strfmt.Registry) error { 96 | 97 | if swag.IsZero(m.RxRateLimiter) { // not required 98 | return nil 99 | } 100 | 101 | if m.RxRateLimiter != nil { 102 | if err := m.RxRateLimiter.Validate(formats); err != nil { 103 | if ve, ok := err.(*errors.Validation); ok { 104 | return ve.ValidateName("rx_rate_limiter") 105 | } 106 | return err 107 | } 108 | } 109 | 110 | return nil 111 | } 112 | 113 | func (m *NetworkInterface) validateTxRateLimiter(formats strfmt.Registry) error { 114 | 115 | if swag.IsZero(m.TxRateLimiter) { // not required 116 | return nil 117 | } 118 | 119 | if m.TxRateLimiter != nil { 120 | if err := m.TxRateLimiter.Validate(formats); err != nil { 121 | if ve, ok := err.(*errors.Validation); ok { 122 | return ve.ValidateName("tx_rate_limiter") 123 | } 124 | return err 125 | } 126 | } 127 | 128 | return nil 129 | } 130 | 131 | // MarshalBinary interface implementation 132 | func (m *NetworkInterface) MarshalBinary() ([]byte, error) { 133 | if m == nil { 134 | return nil, nil 135 | } 136 | return swag.WriteJSON(m) 137 | } 138 | 139 | // UnmarshalBinary interface implementation 140 | func (m *NetworkInterface) UnmarshalBinary(b []byte) error { 141 | var res NetworkInterface 142 | if err := swag.ReadJSON(b, &res); err != nil { 143 | return err 144 | } 145 | *m = res 146 | return nil 147 | } 148 | -------------------------------------------------------------------------------- /client/models/partial_drive.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // PartialDrive partial drive 30 | // swagger:model PartialDrive 31 | type PartialDrive struct { 32 | 33 | // drive id 34 | // Required: true 35 | DriveID *string `json:"drive_id"` 36 | 37 | // Host level path for the guest drive 38 | PathOnHost string `json:"path_on_host,omitempty"` 39 | 40 | // rate limiter 41 | RateLimiter *RateLimiter `json:"rate_limiter,omitempty"` 42 | } 43 | 44 | // Validate validates this partial drive 45 | func (m *PartialDrive) Validate(formats strfmt.Registry) error { 46 | var res []error 47 | 48 | if err := m.validateDriveID(formats); err != nil { 49 | res = append(res, err) 50 | } 51 | 52 | if err := m.validateRateLimiter(formats); err != nil { 53 | res = append(res, err) 54 | } 55 | 56 | if len(res) > 0 { 57 | return errors.CompositeValidationError(res...) 58 | } 59 | return nil 60 | } 61 | 62 | func (m *PartialDrive) validateDriveID(formats strfmt.Registry) error { 63 | 64 | if err := validate.Required("drive_id", "body", m.DriveID); err != nil { 65 | return err 66 | } 67 | 68 | return nil 69 | } 70 | 71 | func (m *PartialDrive) validateRateLimiter(formats strfmt.Registry) error { 72 | 73 | if swag.IsZero(m.RateLimiter) { // not required 74 | return nil 75 | } 76 | 77 | if m.RateLimiter != nil { 78 | if err := m.RateLimiter.Validate(formats); err != nil { 79 | if ve, ok := err.(*errors.Validation); ok { 80 | return ve.ValidateName("rate_limiter") 81 | } 82 | return err 83 | } 84 | } 85 | 86 | return nil 87 | } 88 | 89 | // MarshalBinary interface implementation 90 | func (m *PartialDrive) MarshalBinary() ([]byte, error) { 91 | if m == nil { 92 | return nil, nil 93 | } 94 | return swag.WriteJSON(m) 95 | } 96 | 97 | // UnmarshalBinary interface implementation 98 | func (m *PartialDrive) UnmarshalBinary(b []byte) error { 99 | var res PartialDrive 100 | if err := swag.ReadJSON(b, &res); err != nil { 101 | return err 102 | } 103 | *m = res 104 | return nil 105 | } 106 | -------------------------------------------------------------------------------- /client/models/partial_network_interface.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // PartialNetworkInterface Defines a partial network interface structure, used to update the rate limiters for that interface, after microvm start. 30 | // swagger:model PartialNetworkInterface 31 | type PartialNetworkInterface struct { 32 | 33 | // iface id 34 | // Required: true 35 | IfaceID *string `json:"iface_id"` 36 | 37 | // rx rate limiter 38 | RxRateLimiter *RateLimiter `json:"rx_rate_limiter,omitempty"` 39 | 40 | // tx rate limiter 41 | TxRateLimiter *RateLimiter `json:"tx_rate_limiter,omitempty"` 42 | } 43 | 44 | // Validate validates this partial network interface 45 | func (m *PartialNetworkInterface) Validate(formats strfmt.Registry) error { 46 | var res []error 47 | 48 | if err := m.validateIfaceID(formats); err != nil { 49 | res = append(res, err) 50 | } 51 | 52 | if err := m.validateRxRateLimiter(formats); err != nil { 53 | res = append(res, err) 54 | } 55 | 56 | if err := m.validateTxRateLimiter(formats); err != nil { 57 | res = append(res, err) 58 | } 59 | 60 | if len(res) > 0 { 61 | return errors.CompositeValidationError(res...) 62 | } 63 | return nil 64 | } 65 | 66 | func (m *PartialNetworkInterface) validateIfaceID(formats strfmt.Registry) error { 67 | 68 | if err := validate.Required("iface_id", "body", m.IfaceID); err != nil { 69 | return err 70 | } 71 | 72 | return nil 73 | } 74 | 75 | func (m *PartialNetworkInterface) validateRxRateLimiter(formats strfmt.Registry) error { 76 | 77 | if swag.IsZero(m.RxRateLimiter) { // not required 78 | return nil 79 | } 80 | 81 | if m.RxRateLimiter != nil { 82 | if err := m.RxRateLimiter.Validate(formats); err != nil { 83 | if ve, ok := err.(*errors.Validation); ok { 84 | return ve.ValidateName("rx_rate_limiter") 85 | } 86 | return err 87 | } 88 | } 89 | 90 | return nil 91 | } 92 | 93 | func (m *PartialNetworkInterface) validateTxRateLimiter(formats strfmt.Registry) error { 94 | 95 | if swag.IsZero(m.TxRateLimiter) { // not required 96 | return nil 97 | } 98 | 99 | if m.TxRateLimiter != nil { 100 | if err := m.TxRateLimiter.Validate(formats); err != nil { 101 | if ve, ok := err.(*errors.Validation); ok { 102 | return ve.ValidateName("tx_rate_limiter") 103 | } 104 | return err 105 | } 106 | } 107 | 108 | return nil 109 | } 110 | 111 | // MarshalBinary interface implementation 112 | func (m *PartialNetworkInterface) MarshalBinary() ([]byte, error) { 113 | if m == nil { 114 | return nil, nil 115 | } 116 | return swag.WriteJSON(m) 117 | } 118 | 119 | // UnmarshalBinary interface implementation 120 | func (m *PartialNetworkInterface) UnmarshalBinary(b []byte) error { 121 | var res PartialNetworkInterface 122 | if err := swag.ReadJSON(b, &res); err != nil { 123 | return err 124 | } 125 | *m = res 126 | return nil 127 | } 128 | -------------------------------------------------------------------------------- /client/models/rate_limiter.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | ) 27 | 28 | // RateLimiter Defines an IO rate limiter with independent bytes/s and ops/s limits. Limits are defined by configuring each of the _bandwidth_ and _ops_ token buckets. 29 | // swagger:model RateLimiter 30 | type RateLimiter struct { 31 | 32 | // Token bucket with bytes as tokens 33 | Bandwidth *TokenBucket `json:"bandwidth,omitempty"` 34 | 35 | // Token bucket with operations as tokens 36 | Ops *TokenBucket `json:"ops,omitempty"` 37 | } 38 | 39 | // Validate validates this rate limiter 40 | func (m *RateLimiter) Validate(formats strfmt.Registry) error { 41 | var res []error 42 | 43 | if err := m.validateBandwidth(formats); err != nil { 44 | res = append(res, err) 45 | } 46 | 47 | if err := m.validateOps(formats); err != nil { 48 | res = append(res, err) 49 | } 50 | 51 | if len(res) > 0 { 52 | return errors.CompositeValidationError(res...) 53 | } 54 | return nil 55 | } 56 | 57 | func (m *RateLimiter) validateBandwidth(formats strfmt.Registry) error { 58 | 59 | if swag.IsZero(m.Bandwidth) { // not required 60 | return nil 61 | } 62 | 63 | if m.Bandwidth != nil { 64 | if err := m.Bandwidth.Validate(formats); err != nil { 65 | if ve, ok := err.(*errors.Validation); ok { 66 | return ve.ValidateName("bandwidth") 67 | } 68 | return err 69 | } 70 | } 71 | 72 | return nil 73 | } 74 | 75 | func (m *RateLimiter) validateOps(formats strfmt.Registry) error { 76 | 77 | if swag.IsZero(m.Ops) { // not required 78 | return nil 79 | } 80 | 81 | if m.Ops != nil { 82 | if err := m.Ops.Validate(formats); err != nil { 83 | if ve, ok := err.(*errors.Validation); ok { 84 | return ve.ValidateName("ops") 85 | } 86 | return err 87 | } 88 | } 89 | 90 | return nil 91 | } 92 | 93 | // MarshalBinary interface implementation 94 | func (m *RateLimiter) MarshalBinary() ([]byte, error) { 95 | if m == nil { 96 | return nil, nil 97 | } 98 | return swag.WriteJSON(m) 99 | } 100 | 101 | // UnmarshalBinary interface implementation 102 | func (m *RateLimiter) UnmarshalBinary(b []byte) error { 103 | var res RateLimiter 104 | if err := swag.ReadJSON(b, &res); err != nil { 105 | return err 106 | } 107 | *m = res 108 | return nil 109 | } 110 | -------------------------------------------------------------------------------- /client/models/snapshot_load_params.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // SnapshotLoadParams Defines the configuration used for handling snapshot resume. Exactly one of the two `mem_*` fields must be present in the body of the request. 30 | // swagger:model SnapshotLoadParams 31 | type SnapshotLoadParams struct { 32 | 33 | // Enable support for incremental (diff) snapshots by tracking dirty guest pages. 34 | EnableDiffSnapshots bool `json:"enable_diff_snapshots,omitempty"` 35 | 36 | // Configuration for the backend that handles memory load. If this field is specified, `mem_file_path` is forbidden. Either `mem_backend` or `mem_file_path` must be present at a time. 37 | MemBackend *MemoryBackend `json:"mem_backend,omitempty"` 38 | 39 | // Path to the file that contains the guest memory to be loaded. This parameter has been deprecated and is only allowed if `mem_backend` is not present. 40 | MemFilePath string `json:"mem_file_path,omitempty"` 41 | 42 | // When set to true, the vm is also resumed if the snapshot load is successful. 43 | ResumeVM bool `json:"resume_vm,omitempty"` 44 | 45 | // Path to the file that contains the microVM state to be loaded. 46 | // Required: true 47 | SnapshotPath *string `json:"snapshot_path"` 48 | } 49 | 50 | // Validate validates this snapshot load params 51 | func (m *SnapshotLoadParams) Validate(formats strfmt.Registry) error { 52 | var res []error 53 | 54 | if err := m.validateMemBackend(formats); err != nil { 55 | res = append(res, err) 56 | } 57 | 58 | if err := m.validateSnapshotPath(formats); err != nil { 59 | res = append(res, err) 60 | } 61 | 62 | if len(res) > 0 { 63 | return errors.CompositeValidationError(res...) 64 | } 65 | return nil 66 | } 67 | 68 | func (m *SnapshotLoadParams) validateMemBackend(formats strfmt.Registry) error { 69 | 70 | if swag.IsZero(m.MemBackend) { // not required 71 | return nil 72 | } 73 | 74 | if m.MemBackend != nil { 75 | if err := m.MemBackend.Validate(formats); err != nil { 76 | if ve, ok := err.(*errors.Validation); ok { 77 | return ve.ValidateName("mem_backend") 78 | } 79 | return err 80 | } 81 | } 82 | 83 | return nil 84 | } 85 | 86 | func (m *SnapshotLoadParams) validateSnapshotPath(formats strfmt.Registry) error { 87 | 88 | if err := validate.Required("snapshot_path", "body", m.SnapshotPath); err != nil { 89 | return err 90 | } 91 | 92 | return nil 93 | } 94 | 95 | // MarshalBinary interface implementation 96 | func (m *SnapshotLoadParams) MarshalBinary() ([]byte, error) { 97 | if m == nil { 98 | return nil, nil 99 | } 100 | return swag.WriteJSON(m) 101 | } 102 | 103 | // UnmarshalBinary interface implementation 104 | func (m *SnapshotLoadParams) UnmarshalBinary(b []byte) error { 105 | var res SnapshotLoadParams 106 | if err := swag.ReadJSON(b, &res); err != nil { 107 | return err 108 | } 109 | *m = res 110 | return nil 111 | } 112 | -------------------------------------------------------------------------------- /client/models/token_bucket.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // TokenBucket Defines a token bucket with a maximum capacity (size), an initial burst size (one_time_burst) and an interval for refilling purposes (refill_time). The refill-rate is derived from size and refill_time, and it is the constant rate at which the tokens replenish. The refill process only starts happening after the initial burst budget is consumed. Consumption from the token bucket is unbounded in speed which allows for bursts bound in size by the amount of tokens available. Once the token bucket is empty, consumption speed is bound by the refill_rate. 30 | // swagger:model TokenBucket 31 | type TokenBucket struct { 32 | 33 | // The initial size of a token bucket. 34 | // Minimum: 0 35 | OneTimeBurst *int64 `json:"one_time_burst,omitempty"` 36 | 37 | // The amount of milliseconds it takes for the bucket to refill. 38 | // Required: true 39 | // Minimum: 0 40 | RefillTime *int64 `json:"refill_time"` 41 | 42 | // The total number of tokens this bucket can hold. 43 | // Required: true 44 | // Minimum: 0 45 | Size *int64 `json:"size"` 46 | } 47 | 48 | // Validate validates this token bucket 49 | func (m *TokenBucket) Validate(formats strfmt.Registry) error { 50 | var res []error 51 | 52 | if err := m.validateOneTimeBurst(formats); err != nil { 53 | res = append(res, err) 54 | } 55 | 56 | if err := m.validateRefillTime(formats); err != nil { 57 | res = append(res, err) 58 | } 59 | 60 | if err := m.validateSize(formats); err != nil { 61 | res = append(res, err) 62 | } 63 | 64 | if len(res) > 0 { 65 | return errors.CompositeValidationError(res...) 66 | } 67 | return nil 68 | } 69 | 70 | func (m *TokenBucket) validateOneTimeBurst(formats strfmt.Registry) error { 71 | 72 | if swag.IsZero(m.OneTimeBurst) { // not required 73 | return nil 74 | } 75 | 76 | if err := validate.MinimumInt("one_time_burst", "body", int64(*m.OneTimeBurst), 0, false); err != nil { 77 | return err 78 | } 79 | 80 | return nil 81 | } 82 | 83 | func (m *TokenBucket) validateRefillTime(formats strfmt.Registry) error { 84 | 85 | if err := validate.Required("refill_time", "body", m.RefillTime); err != nil { 86 | return err 87 | } 88 | 89 | if err := validate.MinimumInt("refill_time", "body", int64(*m.RefillTime), 0, false); err != nil { 90 | return err 91 | } 92 | 93 | return nil 94 | } 95 | 96 | func (m *TokenBucket) validateSize(formats strfmt.Registry) error { 97 | 98 | if err := validate.Required("size", "body", m.Size); err != nil { 99 | return err 100 | } 101 | 102 | if err := validate.MinimumInt("size", "body", int64(*m.Size), 0, false); err != nil { 103 | return err 104 | } 105 | 106 | return nil 107 | } 108 | 109 | // MarshalBinary interface implementation 110 | func (m *TokenBucket) MarshalBinary() ([]byte, error) { 111 | if m == nil { 112 | return nil, nil 113 | } 114 | return swag.WriteJSON(m) 115 | } 116 | 117 | // UnmarshalBinary interface implementation 118 | func (m *TokenBucket) UnmarshalBinary(b []byte) error { 119 | var res TokenBucket 120 | if err := swag.ReadJSON(b, &res); err != nil { 121 | return err 122 | } 123 | *m = res 124 | return nil 125 | } 126 | -------------------------------------------------------------------------------- /client/models/vm.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "encoding/json" 23 | 24 | strfmt "github.com/go-openapi/strfmt" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/swag" 28 | "github.com/go-openapi/validate" 29 | ) 30 | 31 | // VM Defines the microVM running state. It is especially useful in the snapshotting context. 32 | // swagger:model Vm 33 | type VM struct { 34 | 35 | // state 36 | // Required: true 37 | // Enum: [Paused Resumed] 38 | State *string `json:"state"` 39 | } 40 | 41 | // Validate validates this Vm 42 | func (m *VM) Validate(formats strfmt.Registry) error { 43 | var res []error 44 | 45 | if err := m.validateState(formats); err != nil { 46 | res = append(res, err) 47 | } 48 | 49 | if len(res) > 0 { 50 | return errors.CompositeValidationError(res...) 51 | } 52 | return nil 53 | } 54 | 55 | var vmTypeStatePropEnum []interface{} 56 | 57 | func init() { 58 | var res []string 59 | if err := json.Unmarshal([]byte(`["Paused","Resumed"]`), &res); err != nil { 60 | panic(err) 61 | } 62 | for _, v := range res { 63 | vmTypeStatePropEnum = append(vmTypeStatePropEnum, v) 64 | } 65 | } 66 | 67 | const ( 68 | 69 | // VMStatePaused captures enum value "Paused" 70 | VMStatePaused string = "Paused" 71 | 72 | // VMStateResumed captures enum value "Resumed" 73 | VMStateResumed string = "Resumed" 74 | ) 75 | 76 | // prop value enum 77 | func (m *VM) validateStateEnum(path, location string, value string) error { 78 | if err := validate.Enum(path, location, value, vmTypeStatePropEnum); err != nil { 79 | return err 80 | } 81 | return nil 82 | } 83 | 84 | func (m *VM) validateState(formats strfmt.Registry) error { 85 | 86 | if err := validate.Required("state", "body", m.State); err != nil { 87 | return err 88 | } 89 | 90 | // value enum 91 | if err := m.validateStateEnum("state", "body", *m.State); err != nil { 92 | return err 93 | } 94 | 95 | return nil 96 | } 97 | 98 | // MarshalBinary interface implementation 99 | func (m *VM) MarshalBinary() ([]byte, error) { 100 | if m == nil { 101 | return nil, nil 102 | } 103 | return swag.WriteJSON(m) 104 | } 105 | 106 | // UnmarshalBinary interface implementation 107 | func (m *VM) UnmarshalBinary(b []byte) error { 108 | var res VM 109 | if err := swag.ReadJSON(b, &res); err != nil { 110 | return err 111 | } 112 | *m = res 113 | return nil 114 | } 115 | -------------------------------------------------------------------------------- /client/models/vsock.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package models 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | "github.com/go-openapi/errors" 25 | "github.com/go-openapi/swag" 26 | "github.com/go-openapi/validate" 27 | ) 28 | 29 | // Vsock Defines a vsock device, backed by a set of Unix Domain Sockets, on the host side. For host-initiated connections, Firecracker will be listening on the Unix socket identified by the path `uds_path`. Firecracker will create this socket, bind and listen on it. Host-initiated connections will be performed by connection to this socket and issuing a connection forwarding request to the desired guest-side vsock port (i.e. `CONNECT 52\n`, to connect to port 52). For guest-initiated connections, Firecracker will expect host software to be bound and listening on Unix sockets at `uds_path_`. E.g. "/path/to/host_vsock.sock_52" for port number 52. 30 | // swagger:model Vsock 31 | type Vsock struct { 32 | 33 | // Guest Vsock CID 34 | // Required: true 35 | // Minimum: 3 36 | GuestCid *int64 `json:"guest_cid"` 37 | 38 | // Path to UNIX domain socket, used to proxy vsock connections. 39 | // Required: true 40 | UdsPath *string `json:"uds_path"` 41 | 42 | // This parameter has been deprecated since v1.0.0. 43 | VsockID string `json:"vsock_id,omitempty"` 44 | } 45 | 46 | // Validate validates this vsock 47 | func (m *Vsock) Validate(formats strfmt.Registry) error { 48 | var res []error 49 | 50 | if err := m.validateGuestCid(formats); err != nil { 51 | res = append(res, err) 52 | } 53 | 54 | if err := m.validateUdsPath(formats); err != nil { 55 | res = append(res, err) 56 | } 57 | 58 | if len(res) > 0 { 59 | return errors.CompositeValidationError(res...) 60 | } 61 | return nil 62 | } 63 | 64 | func (m *Vsock) validateGuestCid(formats strfmt.Registry) error { 65 | 66 | if err := validate.Required("guest_cid", "body", m.GuestCid); err != nil { 67 | return err 68 | } 69 | 70 | if err := validate.MinimumInt("guest_cid", "body", int64(*m.GuestCid), 3, false); err != nil { 71 | return err 72 | } 73 | 74 | return nil 75 | } 76 | 77 | func (m *Vsock) validateUdsPath(formats strfmt.Registry) error { 78 | 79 | if err := validate.Required("uds_path", "body", m.UdsPath); err != nil { 80 | return err 81 | } 82 | 83 | return nil 84 | } 85 | 86 | // MarshalBinary interface implementation 87 | func (m *Vsock) MarshalBinary() ([]byte, error) { 88 | if m == nil { 89 | return nil, nil 90 | } 91 | return swag.WriteJSON(m) 92 | } 93 | 94 | // UnmarshalBinary interface implementation 95 | func (m *Vsock) UnmarshalBinary(b []byte) error { 96 | var res Vsock 97 | if err := swag.ReadJSON(b, &res); err != nil { 98 | return err 99 | } 100 | *m = res 101 | return nil 102 | } 103 | -------------------------------------------------------------------------------- /client/operations/describe_balloon_config_parameters.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "context" 23 | "net/http" 24 | "time" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/runtime" 28 | cr "github.com/go-openapi/runtime/client" 29 | 30 | strfmt "github.com/go-openapi/strfmt" 31 | ) 32 | 33 | // NewDescribeBalloonConfigParams creates a new DescribeBalloonConfigParams object 34 | // with the default values initialized. 35 | func NewDescribeBalloonConfigParams() *DescribeBalloonConfigParams { 36 | 37 | return &DescribeBalloonConfigParams{ 38 | 39 | timeout: cr.DefaultTimeout, 40 | } 41 | } 42 | 43 | // NewDescribeBalloonConfigParamsWithTimeout creates a new DescribeBalloonConfigParams object 44 | // with the default values initialized, and the ability to set a timeout on a request 45 | func NewDescribeBalloonConfigParamsWithTimeout(timeout time.Duration) *DescribeBalloonConfigParams { 46 | 47 | return &DescribeBalloonConfigParams{ 48 | 49 | timeout: timeout, 50 | } 51 | } 52 | 53 | // NewDescribeBalloonConfigParamsWithContext creates a new DescribeBalloonConfigParams object 54 | // with the default values initialized, and the ability to set a context for a request 55 | func NewDescribeBalloonConfigParamsWithContext(ctx context.Context) *DescribeBalloonConfigParams { 56 | 57 | return &DescribeBalloonConfigParams{ 58 | 59 | Context: ctx, 60 | } 61 | } 62 | 63 | // NewDescribeBalloonConfigParamsWithHTTPClient creates a new DescribeBalloonConfigParams object 64 | // with the default values initialized, and the ability to set a custom HTTPClient for a request 65 | func NewDescribeBalloonConfigParamsWithHTTPClient(client *http.Client) *DescribeBalloonConfigParams { 66 | 67 | return &DescribeBalloonConfigParams{ 68 | HTTPClient: client, 69 | } 70 | } 71 | 72 | /*DescribeBalloonConfigParams contains all the parameters to send to the API endpoint 73 | for the describe balloon config operation typically these are written to a http.Request 74 | */ 75 | type DescribeBalloonConfigParams struct { 76 | timeout time.Duration 77 | Context context.Context 78 | HTTPClient *http.Client 79 | } 80 | 81 | // WithTimeout adds the timeout to the describe balloon config params 82 | func (o *DescribeBalloonConfigParams) WithTimeout(timeout time.Duration) *DescribeBalloonConfigParams { 83 | o.SetTimeout(timeout) 84 | return o 85 | } 86 | 87 | // SetTimeout adds the timeout to the describe balloon config params 88 | func (o *DescribeBalloonConfigParams) SetTimeout(timeout time.Duration) { 89 | o.timeout = timeout 90 | } 91 | 92 | // WithContext adds the context to the describe balloon config params 93 | func (o *DescribeBalloonConfigParams) WithContext(ctx context.Context) *DescribeBalloonConfigParams { 94 | o.SetContext(ctx) 95 | return o 96 | } 97 | 98 | // SetContext adds the context to the describe balloon config params 99 | func (o *DescribeBalloonConfigParams) SetContext(ctx context.Context) { 100 | o.Context = ctx 101 | } 102 | 103 | // WithHTTPClient adds the HTTPClient to the describe balloon config params 104 | func (o *DescribeBalloonConfigParams) WithHTTPClient(client *http.Client) *DescribeBalloonConfigParams { 105 | o.SetHTTPClient(client) 106 | return o 107 | } 108 | 109 | // SetHTTPClient adds the HTTPClient to the describe balloon config params 110 | func (o *DescribeBalloonConfigParams) SetHTTPClient(client *http.Client) { 111 | o.HTTPClient = client 112 | } 113 | 114 | // WriteToRequest writes these params to a swagger request 115 | func (o *DescribeBalloonConfigParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { 116 | 117 | if err := r.SetTimeout(o.timeout); err != nil { 118 | return err 119 | } 120 | var res []error 121 | 122 | if len(res) > 0 { 123 | return errors.CompositeValidationError(res...) 124 | } 125 | return nil 126 | } 127 | -------------------------------------------------------------------------------- /client/operations/describe_balloon_stats_parameters.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "context" 23 | "net/http" 24 | "time" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/runtime" 28 | cr "github.com/go-openapi/runtime/client" 29 | 30 | strfmt "github.com/go-openapi/strfmt" 31 | ) 32 | 33 | // NewDescribeBalloonStatsParams creates a new DescribeBalloonStatsParams object 34 | // with the default values initialized. 35 | func NewDescribeBalloonStatsParams() *DescribeBalloonStatsParams { 36 | 37 | return &DescribeBalloonStatsParams{ 38 | 39 | timeout: cr.DefaultTimeout, 40 | } 41 | } 42 | 43 | // NewDescribeBalloonStatsParamsWithTimeout creates a new DescribeBalloonStatsParams object 44 | // with the default values initialized, and the ability to set a timeout on a request 45 | func NewDescribeBalloonStatsParamsWithTimeout(timeout time.Duration) *DescribeBalloonStatsParams { 46 | 47 | return &DescribeBalloonStatsParams{ 48 | 49 | timeout: timeout, 50 | } 51 | } 52 | 53 | // NewDescribeBalloonStatsParamsWithContext creates a new DescribeBalloonStatsParams object 54 | // with the default values initialized, and the ability to set a context for a request 55 | func NewDescribeBalloonStatsParamsWithContext(ctx context.Context) *DescribeBalloonStatsParams { 56 | 57 | return &DescribeBalloonStatsParams{ 58 | 59 | Context: ctx, 60 | } 61 | } 62 | 63 | // NewDescribeBalloonStatsParamsWithHTTPClient creates a new DescribeBalloonStatsParams object 64 | // with the default values initialized, and the ability to set a custom HTTPClient for a request 65 | func NewDescribeBalloonStatsParamsWithHTTPClient(client *http.Client) *DescribeBalloonStatsParams { 66 | 67 | return &DescribeBalloonStatsParams{ 68 | HTTPClient: client, 69 | } 70 | } 71 | 72 | /*DescribeBalloonStatsParams contains all the parameters to send to the API endpoint 73 | for the describe balloon stats operation typically these are written to a http.Request 74 | */ 75 | type DescribeBalloonStatsParams struct { 76 | timeout time.Duration 77 | Context context.Context 78 | HTTPClient *http.Client 79 | } 80 | 81 | // WithTimeout adds the timeout to the describe balloon stats params 82 | func (o *DescribeBalloonStatsParams) WithTimeout(timeout time.Duration) *DescribeBalloonStatsParams { 83 | o.SetTimeout(timeout) 84 | return o 85 | } 86 | 87 | // SetTimeout adds the timeout to the describe balloon stats params 88 | func (o *DescribeBalloonStatsParams) SetTimeout(timeout time.Duration) { 89 | o.timeout = timeout 90 | } 91 | 92 | // WithContext adds the context to the describe balloon stats params 93 | func (o *DescribeBalloonStatsParams) WithContext(ctx context.Context) *DescribeBalloonStatsParams { 94 | o.SetContext(ctx) 95 | return o 96 | } 97 | 98 | // SetContext adds the context to the describe balloon stats params 99 | func (o *DescribeBalloonStatsParams) SetContext(ctx context.Context) { 100 | o.Context = ctx 101 | } 102 | 103 | // WithHTTPClient adds the HTTPClient to the describe balloon stats params 104 | func (o *DescribeBalloonStatsParams) WithHTTPClient(client *http.Client) *DescribeBalloonStatsParams { 105 | o.SetHTTPClient(client) 106 | return o 107 | } 108 | 109 | // SetHTTPClient adds the HTTPClient to the describe balloon stats params 110 | func (o *DescribeBalloonStatsParams) SetHTTPClient(client *http.Client) { 111 | o.HTTPClient = client 112 | } 113 | 114 | // WriteToRequest writes these params to a swagger request 115 | func (o *DescribeBalloonStatsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { 116 | 117 | if err := r.SetTimeout(o.timeout); err != nil { 118 | return err 119 | } 120 | var res []error 121 | 122 | if len(res) > 0 { 123 | return errors.CompositeValidationError(res...) 124 | } 125 | return nil 126 | } 127 | -------------------------------------------------------------------------------- /client/operations/describe_instance_parameters.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "context" 23 | "net/http" 24 | "time" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/runtime" 28 | cr "github.com/go-openapi/runtime/client" 29 | 30 | strfmt "github.com/go-openapi/strfmt" 31 | ) 32 | 33 | // NewDescribeInstanceParams creates a new DescribeInstanceParams object 34 | // with the default values initialized. 35 | func NewDescribeInstanceParams() *DescribeInstanceParams { 36 | 37 | return &DescribeInstanceParams{ 38 | 39 | timeout: cr.DefaultTimeout, 40 | } 41 | } 42 | 43 | // NewDescribeInstanceParamsWithTimeout creates a new DescribeInstanceParams object 44 | // with the default values initialized, and the ability to set a timeout on a request 45 | func NewDescribeInstanceParamsWithTimeout(timeout time.Duration) *DescribeInstanceParams { 46 | 47 | return &DescribeInstanceParams{ 48 | 49 | timeout: timeout, 50 | } 51 | } 52 | 53 | // NewDescribeInstanceParamsWithContext creates a new DescribeInstanceParams object 54 | // with the default values initialized, and the ability to set a context for a request 55 | func NewDescribeInstanceParamsWithContext(ctx context.Context) *DescribeInstanceParams { 56 | 57 | return &DescribeInstanceParams{ 58 | 59 | Context: ctx, 60 | } 61 | } 62 | 63 | // NewDescribeInstanceParamsWithHTTPClient creates a new DescribeInstanceParams object 64 | // with the default values initialized, and the ability to set a custom HTTPClient for a request 65 | func NewDescribeInstanceParamsWithHTTPClient(client *http.Client) *DescribeInstanceParams { 66 | 67 | return &DescribeInstanceParams{ 68 | HTTPClient: client, 69 | } 70 | } 71 | 72 | /*DescribeInstanceParams contains all the parameters to send to the API endpoint 73 | for the describe instance operation typically these are written to a http.Request 74 | */ 75 | type DescribeInstanceParams struct { 76 | timeout time.Duration 77 | Context context.Context 78 | HTTPClient *http.Client 79 | } 80 | 81 | // WithTimeout adds the timeout to the describe instance params 82 | func (o *DescribeInstanceParams) WithTimeout(timeout time.Duration) *DescribeInstanceParams { 83 | o.SetTimeout(timeout) 84 | return o 85 | } 86 | 87 | // SetTimeout adds the timeout to the describe instance params 88 | func (o *DescribeInstanceParams) SetTimeout(timeout time.Duration) { 89 | o.timeout = timeout 90 | } 91 | 92 | // WithContext adds the context to the describe instance params 93 | func (o *DescribeInstanceParams) WithContext(ctx context.Context) *DescribeInstanceParams { 94 | o.SetContext(ctx) 95 | return o 96 | } 97 | 98 | // SetContext adds the context to the describe instance params 99 | func (o *DescribeInstanceParams) SetContext(ctx context.Context) { 100 | o.Context = ctx 101 | } 102 | 103 | // WithHTTPClient adds the HTTPClient to the describe instance params 104 | func (o *DescribeInstanceParams) WithHTTPClient(client *http.Client) *DescribeInstanceParams { 105 | o.SetHTTPClient(client) 106 | return o 107 | } 108 | 109 | // SetHTTPClient adds the HTTPClient to the describe instance params 110 | func (o *DescribeInstanceParams) SetHTTPClient(client *http.Client) { 111 | o.HTTPClient = client 112 | } 113 | 114 | // WriteToRequest writes these params to a swagger request 115 | func (o *DescribeInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { 116 | 117 | if err := r.SetTimeout(o.timeout); err != nil { 118 | return err 119 | } 120 | var res []error 121 | 122 | if len(res) > 0 { 123 | return errors.CompositeValidationError(res...) 124 | } 125 | return nil 126 | } 127 | -------------------------------------------------------------------------------- /client/operations/describe_instance_responses.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "fmt" 23 | "io" 24 | 25 | "github.com/go-openapi/runtime" 26 | 27 | strfmt "github.com/go-openapi/strfmt" 28 | 29 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 30 | ) 31 | 32 | // DescribeInstanceReader is a Reader for the DescribeInstance structure. 33 | type DescribeInstanceReader struct { 34 | formats strfmt.Registry 35 | } 36 | 37 | // ReadResponse reads a server response into the received o. 38 | func (o *DescribeInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { 39 | switch response.Code() { 40 | case 200: 41 | result := NewDescribeInstanceOK() 42 | if err := result.readResponse(response, consumer, o.formats); err != nil { 43 | return nil, err 44 | } 45 | return result, nil 46 | default: 47 | result := NewDescribeInstanceDefault(response.Code()) 48 | if err := result.readResponse(response, consumer, o.formats); err != nil { 49 | return nil, err 50 | } 51 | if response.Code()/100 == 2 { 52 | return result, nil 53 | } 54 | return nil, result 55 | } 56 | } 57 | 58 | // NewDescribeInstanceOK creates a DescribeInstanceOK with default headers values 59 | func NewDescribeInstanceOK() *DescribeInstanceOK { 60 | return &DescribeInstanceOK{} 61 | } 62 | 63 | /*DescribeInstanceOK handles this case with default header values. 64 | 65 | The instance information 66 | */ 67 | type DescribeInstanceOK struct { 68 | Payload *models.InstanceInfo 69 | } 70 | 71 | func (o *DescribeInstanceOK) Error() string { 72 | return fmt.Sprintf("[GET /][%d] describeInstanceOK %+v", 200, o.Payload) 73 | } 74 | 75 | func (o *DescribeInstanceOK) GetPayload() *models.InstanceInfo { 76 | return o.Payload 77 | } 78 | 79 | func (o *DescribeInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 80 | 81 | o.Payload = new(models.InstanceInfo) 82 | 83 | // response payload 84 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 85 | return err 86 | } 87 | 88 | return nil 89 | } 90 | 91 | // NewDescribeInstanceDefault creates a DescribeInstanceDefault with default headers values 92 | func NewDescribeInstanceDefault(code int) *DescribeInstanceDefault { 93 | return &DescribeInstanceDefault{ 94 | _statusCode: code, 95 | } 96 | } 97 | 98 | /*DescribeInstanceDefault handles this case with default header values. 99 | 100 | Internal Server Error 101 | */ 102 | type DescribeInstanceDefault struct { 103 | _statusCode int 104 | 105 | Payload *models.Error 106 | } 107 | 108 | // Code gets the status code for the describe instance default response 109 | func (o *DescribeInstanceDefault) Code() int { 110 | return o._statusCode 111 | } 112 | 113 | func (o *DescribeInstanceDefault) Error() string { 114 | return fmt.Sprintf("[GET /][%d] describeInstance default %+v", o._statusCode, o.Payload) 115 | } 116 | 117 | func (o *DescribeInstanceDefault) GetPayload() *models.Error { 118 | return o.Payload 119 | } 120 | 121 | func (o *DescribeInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 122 | 123 | o.Payload = new(models.Error) 124 | 125 | // response payload 126 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 127 | return err 128 | } 129 | 130 | return nil 131 | } 132 | -------------------------------------------------------------------------------- /client/operations/get_export_vm_config_parameters.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "context" 23 | "net/http" 24 | "time" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/runtime" 28 | cr "github.com/go-openapi/runtime/client" 29 | 30 | strfmt "github.com/go-openapi/strfmt" 31 | ) 32 | 33 | // NewGetExportVMConfigParams creates a new GetExportVMConfigParams object 34 | // with the default values initialized. 35 | func NewGetExportVMConfigParams() *GetExportVMConfigParams { 36 | 37 | return &GetExportVMConfigParams{ 38 | 39 | timeout: cr.DefaultTimeout, 40 | } 41 | } 42 | 43 | // NewGetExportVMConfigParamsWithTimeout creates a new GetExportVMConfigParams object 44 | // with the default values initialized, and the ability to set a timeout on a request 45 | func NewGetExportVMConfigParamsWithTimeout(timeout time.Duration) *GetExportVMConfigParams { 46 | 47 | return &GetExportVMConfigParams{ 48 | 49 | timeout: timeout, 50 | } 51 | } 52 | 53 | // NewGetExportVMConfigParamsWithContext creates a new GetExportVMConfigParams object 54 | // with the default values initialized, and the ability to set a context for a request 55 | func NewGetExportVMConfigParamsWithContext(ctx context.Context) *GetExportVMConfigParams { 56 | 57 | return &GetExportVMConfigParams{ 58 | 59 | Context: ctx, 60 | } 61 | } 62 | 63 | // NewGetExportVMConfigParamsWithHTTPClient creates a new GetExportVMConfigParams object 64 | // with the default values initialized, and the ability to set a custom HTTPClient for a request 65 | func NewGetExportVMConfigParamsWithHTTPClient(client *http.Client) *GetExportVMConfigParams { 66 | 67 | return &GetExportVMConfigParams{ 68 | HTTPClient: client, 69 | } 70 | } 71 | 72 | /*GetExportVMConfigParams contains all the parameters to send to the API endpoint 73 | for the get export Vm config operation typically these are written to a http.Request 74 | */ 75 | type GetExportVMConfigParams struct { 76 | timeout time.Duration 77 | Context context.Context 78 | HTTPClient *http.Client 79 | } 80 | 81 | // WithTimeout adds the timeout to the get export Vm config params 82 | func (o *GetExportVMConfigParams) WithTimeout(timeout time.Duration) *GetExportVMConfigParams { 83 | o.SetTimeout(timeout) 84 | return o 85 | } 86 | 87 | // SetTimeout adds the timeout to the get export Vm config params 88 | func (o *GetExportVMConfigParams) SetTimeout(timeout time.Duration) { 89 | o.timeout = timeout 90 | } 91 | 92 | // WithContext adds the context to the get export Vm config params 93 | func (o *GetExportVMConfigParams) WithContext(ctx context.Context) *GetExportVMConfigParams { 94 | o.SetContext(ctx) 95 | return o 96 | } 97 | 98 | // SetContext adds the context to the get export Vm config params 99 | func (o *GetExportVMConfigParams) SetContext(ctx context.Context) { 100 | o.Context = ctx 101 | } 102 | 103 | // WithHTTPClient adds the HTTPClient to the get export Vm config params 104 | func (o *GetExportVMConfigParams) WithHTTPClient(client *http.Client) *GetExportVMConfigParams { 105 | o.SetHTTPClient(client) 106 | return o 107 | } 108 | 109 | // SetHTTPClient adds the HTTPClient to the get export Vm config params 110 | func (o *GetExportVMConfigParams) SetHTTPClient(client *http.Client) { 111 | o.HTTPClient = client 112 | } 113 | 114 | // WriteToRequest writes these params to a swagger request 115 | func (o *GetExportVMConfigParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { 116 | 117 | if err := r.SetTimeout(o.timeout); err != nil { 118 | return err 119 | } 120 | var res []error 121 | 122 | if len(res) > 0 { 123 | return errors.CompositeValidationError(res...) 124 | } 125 | return nil 126 | } 127 | -------------------------------------------------------------------------------- /client/operations/get_export_vm_config_responses.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "fmt" 23 | "io" 24 | 25 | "github.com/go-openapi/runtime" 26 | 27 | strfmt "github.com/go-openapi/strfmt" 28 | 29 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 30 | ) 31 | 32 | // GetExportVMConfigReader is a Reader for the GetExportVMConfig structure. 33 | type GetExportVMConfigReader struct { 34 | formats strfmt.Registry 35 | } 36 | 37 | // ReadResponse reads a server response into the received o. 38 | func (o *GetExportVMConfigReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { 39 | switch response.Code() { 40 | case 200: 41 | result := NewGetExportVMConfigOK() 42 | if err := result.readResponse(response, consumer, o.formats); err != nil { 43 | return nil, err 44 | } 45 | return result, nil 46 | default: 47 | result := NewGetExportVMConfigDefault(response.Code()) 48 | if err := result.readResponse(response, consumer, o.formats); err != nil { 49 | return nil, err 50 | } 51 | if response.Code()/100 == 2 { 52 | return result, nil 53 | } 54 | return nil, result 55 | } 56 | } 57 | 58 | // NewGetExportVMConfigOK creates a GetExportVMConfigOK with default headers values 59 | func NewGetExportVMConfigOK() *GetExportVMConfigOK { 60 | return &GetExportVMConfigOK{} 61 | } 62 | 63 | /*GetExportVMConfigOK handles this case with default header values. 64 | 65 | OK 66 | */ 67 | type GetExportVMConfigOK struct { 68 | Payload *models.FullVMConfiguration 69 | } 70 | 71 | func (o *GetExportVMConfigOK) Error() string { 72 | return fmt.Sprintf("[GET /vm/config][%d] getExportVmConfigOK %+v", 200, o.Payload) 73 | } 74 | 75 | func (o *GetExportVMConfigOK) GetPayload() *models.FullVMConfiguration { 76 | return o.Payload 77 | } 78 | 79 | func (o *GetExportVMConfigOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 80 | 81 | o.Payload = new(models.FullVMConfiguration) 82 | 83 | // response payload 84 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 85 | return err 86 | } 87 | 88 | return nil 89 | } 90 | 91 | // NewGetExportVMConfigDefault creates a GetExportVMConfigDefault with default headers values 92 | func NewGetExportVMConfigDefault(code int) *GetExportVMConfigDefault { 93 | return &GetExportVMConfigDefault{ 94 | _statusCode: code, 95 | } 96 | } 97 | 98 | /*GetExportVMConfigDefault handles this case with default header values. 99 | 100 | Internal server error 101 | */ 102 | type GetExportVMConfigDefault struct { 103 | _statusCode int 104 | 105 | Payload *models.Error 106 | } 107 | 108 | // Code gets the status code for the get export Vm config default response 109 | func (o *GetExportVMConfigDefault) Code() int { 110 | return o._statusCode 111 | } 112 | 113 | func (o *GetExportVMConfigDefault) Error() string { 114 | return fmt.Sprintf("[GET /vm/config][%d] getExportVmConfig default %+v", o._statusCode, o.Payload) 115 | } 116 | 117 | func (o *GetExportVMConfigDefault) GetPayload() *models.Error { 118 | return o.Payload 119 | } 120 | 121 | func (o *GetExportVMConfigDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 122 | 123 | o.Payload = new(models.Error) 124 | 125 | // response payload 126 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 127 | return err 128 | } 129 | 130 | return nil 131 | } 132 | -------------------------------------------------------------------------------- /client/operations/get_firecracker_version_responses.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "fmt" 23 | "io" 24 | 25 | "github.com/go-openapi/runtime" 26 | 27 | strfmt "github.com/go-openapi/strfmt" 28 | 29 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 30 | ) 31 | 32 | // GetFirecrackerVersionReader is a Reader for the GetFirecrackerVersion structure. 33 | type GetFirecrackerVersionReader struct { 34 | formats strfmt.Registry 35 | } 36 | 37 | // ReadResponse reads a server response into the received o. 38 | func (o *GetFirecrackerVersionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { 39 | switch response.Code() { 40 | case 200: 41 | result := NewGetFirecrackerVersionOK() 42 | if err := result.readResponse(response, consumer, o.formats); err != nil { 43 | return nil, err 44 | } 45 | return result, nil 46 | default: 47 | result := NewGetFirecrackerVersionDefault(response.Code()) 48 | if err := result.readResponse(response, consumer, o.formats); err != nil { 49 | return nil, err 50 | } 51 | if response.Code()/100 == 2 { 52 | return result, nil 53 | } 54 | return nil, result 55 | } 56 | } 57 | 58 | // NewGetFirecrackerVersionOK creates a GetFirecrackerVersionOK with default headers values 59 | func NewGetFirecrackerVersionOK() *GetFirecrackerVersionOK { 60 | return &GetFirecrackerVersionOK{} 61 | } 62 | 63 | /*GetFirecrackerVersionOK handles this case with default header values. 64 | 65 | OK 66 | */ 67 | type GetFirecrackerVersionOK struct { 68 | Payload *models.FirecrackerVersion 69 | } 70 | 71 | func (o *GetFirecrackerVersionOK) Error() string { 72 | return fmt.Sprintf("[GET /version][%d] getFirecrackerVersionOK %+v", 200, o.Payload) 73 | } 74 | 75 | func (o *GetFirecrackerVersionOK) GetPayload() *models.FirecrackerVersion { 76 | return o.Payload 77 | } 78 | 79 | func (o *GetFirecrackerVersionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 80 | 81 | o.Payload = new(models.FirecrackerVersion) 82 | 83 | // response payload 84 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 85 | return err 86 | } 87 | 88 | return nil 89 | } 90 | 91 | // NewGetFirecrackerVersionDefault creates a GetFirecrackerVersionDefault with default headers values 92 | func NewGetFirecrackerVersionDefault(code int) *GetFirecrackerVersionDefault { 93 | return &GetFirecrackerVersionDefault{ 94 | _statusCode: code, 95 | } 96 | } 97 | 98 | /*GetFirecrackerVersionDefault handles this case with default header values. 99 | 100 | Internal server error 101 | */ 102 | type GetFirecrackerVersionDefault struct { 103 | _statusCode int 104 | 105 | Payload *models.Error 106 | } 107 | 108 | // Code gets the status code for the get firecracker version default response 109 | func (o *GetFirecrackerVersionDefault) Code() int { 110 | return o._statusCode 111 | } 112 | 113 | func (o *GetFirecrackerVersionDefault) Error() string { 114 | return fmt.Sprintf("[GET /version][%d] getFirecrackerVersion default %+v", o._statusCode, o.Payload) 115 | } 116 | 117 | func (o *GetFirecrackerVersionDefault) GetPayload() *models.Error { 118 | return o.Payload 119 | } 120 | 121 | func (o *GetFirecrackerVersionDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 122 | 123 | o.Payload = new(models.Error) 124 | 125 | // response payload 126 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 127 | return err 128 | } 129 | 130 | return nil 131 | } 132 | -------------------------------------------------------------------------------- /client/operations/get_machine_configuration_responses.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "fmt" 23 | "io" 24 | 25 | "github.com/go-openapi/runtime" 26 | 27 | strfmt "github.com/go-openapi/strfmt" 28 | 29 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 30 | ) 31 | 32 | // GetMachineConfigurationReader is a Reader for the GetMachineConfiguration structure. 33 | type GetMachineConfigurationReader struct { 34 | formats strfmt.Registry 35 | } 36 | 37 | // ReadResponse reads a server response into the received o. 38 | func (o *GetMachineConfigurationReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { 39 | switch response.Code() { 40 | case 200: 41 | result := NewGetMachineConfigurationOK() 42 | if err := result.readResponse(response, consumer, o.formats); err != nil { 43 | return nil, err 44 | } 45 | return result, nil 46 | default: 47 | result := NewGetMachineConfigurationDefault(response.Code()) 48 | if err := result.readResponse(response, consumer, o.formats); err != nil { 49 | return nil, err 50 | } 51 | if response.Code()/100 == 2 { 52 | return result, nil 53 | } 54 | return nil, result 55 | } 56 | } 57 | 58 | // NewGetMachineConfigurationOK creates a GetMachineConfigurationOK with default headers values 59 | func NewGetMachineConfigurationOK() *GetMachineConfigurationOK { 60 | return &GetMachineConfigurationOK{} 61 | } 62 | 63 | /*GetMachineConfigurationOK handles this case with default header values. 64 | 65 | OK 66 | */ 67 | type GetMachineConfigurationOK struct { 68 | Payload *models.MachineConfiguration 69 | } 70 | 71 | func (o *GetMachineConfigurationOK) Error() string { 72 | return fmt.Sprintf("[GET /machine-config][%d] getMachineConfigurationOK %+v", 200, o.Payload) 73 | } 74 | 75 | func (o *GetMachineConfigurationOK) GetPayload() *models.MachineConfiguration { 76 | return o.Payload 77 | } 78 | 79 | func (o *GetMachineConfigurationOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 80 | 81 | o.Payload = new(models.MachineConfiguration) 82 | 83 | // response payload 84 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 85 | return err 86 | } 87 | 88 | return nil 89 | } 90 | 91 | // NewGetMachineConfigurationDefault creates a GetMachineConfigurationDefault with default headers values 92 | func NewGetMachineConfigurationDefault(code int) *GetMachineConfigurationDefault { 93 | return &GetMachineConfigurationDefault{ 94 | _statusCode: code, 95 | } 96 | } 97 | 98 | /*GetMachineConfigurationDefault handles this case with default header values. 99 | 100 | Internal server error 101 | */ 102 | type GetMachineConfigurationDefault struct { 103 | _statusCode int 104 | 105 | Payload *models.Error 106 | } 107 | 108 | // Code gets the status code for the get machine configuration default response 109 | func (o *GetMachineConfigurationDefault) Code() int { 110 | return o._statusCode 111 | } 112 | 113 | func (o *GetMachineConfigurationDefault) Error() string { 114 | return fmt.Sprintf("[GET /machine-config][%d] getMachineConfiguration default %+v", o._statusCode, o.Payload) 115 | } 116 | 117 | func (o *GetMachineConfigurationDefault) GetPayload() *models.Error { 118 | return o.Payload 119 | } 120 | 121 | func (o *GetMachineConfigurationDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 122 | 123 | o.Payload = new(models.Error) 124 | 125 | // response payload 126 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 127 | return err 128 | } 129 | 130 | return nil 131 | } 132 | -------------------------------------------------------------------------------- /client/operations/get_mmds_parameters.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "context" 23 | "net/http" 24 | "time" 25 | 26 | "github.com/go-openapi/errors" 27 | "github.com/go-openapi/runtime" 28 | cr "github.com/go-openapi/runtime/client" 29 | 30 | strfmt "github.com/go-openapi/strfmt" 31 | ) 32 | 33 | // NewGetMmdsParams creates a new GetMmdsParams object 34 | // with the default values initialized. 35 | func NewGetMmdsParams() *GetMmdsParams { 36 | 37 | return &GetMmdsParams{ 38 | 39 | timeout: cr.DefaultTimeout, 40 | } 41 | } 42 | 43 | // NewGetMmdsParamsWithTimeout creates a new GetMmdsParams object 44 | // with the default values initialized, and the ability to set a timeout on a request 45 | func NewGetMmdsParamsWithTimeout(timeout time.Duration) *GetMmdsParams { 46 | 47 | return &GetMmdsParams{ 48 | 49 | timeout: timeout, 50 | } 51 | } 52 | 53 | // NewGetMmdsParamsWithContext creates a new GetMmdsParams object 54 | // with the default values initialized, and the ability to set a context for a request 55 | func NewGetMmdsParamsWithContext(ctx context.Context) *GetMmdsParams { 56 | 57 | return &GetMmdsParams{ 58 | 59 | Context: ctx, 60 | } 61 | } 62 | 63 | // NewGetMmdsParamsWithHTTPClient creates a new GetMmdsParams object 64 | // with the default values initialized, and the ability to set a custom HTTPClient for a request 65 | func NewGetMmdsParamsWithHTTPClient(client *http.Client) *GetMmdsParams { 66 | 67 | return &GetMmdsParams{ 68 | HTTPClient: client, 69 | } 70 | } 71 | 72 | /*GetMmdsParams contains all the parameters to send to the API endpoint 73 | for the get mmds operation typically these are written to a http.Request 74 | */ 75 | type GetMmdsParams struct { 76 | timeout time.Duration 77 | Context context.Context 78 | HTTPClient *http.Client 79 | } 80 | 81 | // WithTimeout adds the timeout to the get mmds params 82 | func (o *GetMmdsParams) WithTimeout(timeout time.Duration) *GetMmdsParams { 83 | o.SetTimeout(timeout) 84 | return o 85 | } 86 | 87 | // SetTimeout adds the timeout to the get mmds params 88 | func (o *GetMmdsParams) SetTimeout(timeout time.Duration) { 89 | o.timeout = timeout 90 | } 91 | 92 | // WithContext adds the context to the get mmds params 93 | func (o *GetMmdsParams) WithContext(ctx context.Context) *GetMmdsParams { 94 | o.SetContext(ctx) 95 | return o 96 | } 97 | 98 | // SetContext adds the context to the get mmds params 99 | func (o *GetMmdsParams) SetContext(ctx context.Context) { 100 | o.Context = ctx 101 | } 102 | 103 | // WithHTTPClient adds the HTTPClient to the get mmds params 104 | func (o *GetMmdsParams) WithHTTPClient(client *http.Client) *GetMmdsParams { 105 | o.SetHTTPClient(client) 106 | return o 107 | } 108 | 109 | // SetHTTPClient adds the HTTPClient to the get mmds params 110 | func (o *GetMmdsParams) SetHTTPClient(client *http.Client) { 111 | o.HTTPClient = client 112 | } 113 | 114 | // WriteToRequest writes these params to a swagger request 115 | func (o *GetMmdsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { 116 | 117 | if err := r.SetTimeout(o.timeout); err != nil { 118 | return err 119 | } 120 | var res []error 121 | 122 | if len(res) > 0 { 123 | return errors.CompositeValidationError(res...) 124 | } 125 | return nil 126 | } 127 | -------------------------------------------------------------------------------- /client/operations/put_entropy_device_responses.go: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 6 | // not use this file except in compliance with the License. A copy of the 7 | // License is located at 8 | // 9 | // http://aws.amazon.com/apache2.0/ 10 | // 11 | // or in the "license" file accompanying this file. This file is distributed 12 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | // express or implied. See the License for the specific language governing 14 | // permissions and limitations under the License. 15 | 16 | package operations 17 | 18 | // This file was generated by the swagger tool. 19 | // Editing this file might prove futile when you re-run the swagger generate command 20 | 21 | import ( 22 | "fmt" 23 | "io" 24 | 25 | "github.com/go-openapi/runtime" 26 | 27 | strfmt "github.com/go-openapi/strfmt" 28 | 29 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 30 | ) 31 | 32 | // PutEntropyDeviceReader is a Reader for the PutEntropyDevice structure. 33 | type PutEntropyDeviceReader struct { 34 | formats strfmt.Registry 35 | } 36 | 37 | // ReadResponse reads a server response into the received o. 38 | func (o *PutEntropyDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { 39 | switch response.Code() { 40 | case 204: 41 | result := NewPutEntropyDeviceNoContent() 42 | if err := result.readResponse(response, consumer, o.formats); err != nil { 43 | return nil, err 44 | } 45 | return result, nil 46 | default: 47 | result := NewPutEntropyDeviceDefault(response.Code()) 48 | if err := result.readResponse(response, consumer, o.formats); err != nil { 49 | return nil, err 50 | } 51 | if response.Code()/100 == 2 { 52 | return result, nil 53 | } 54 | return nil, result 55 | } 56 | } 57 | 58 | // NewPutEntropyDeviceNoContent creates a PutEntropyDeviceNoContent with default headers values 59 | func NewPutEntropyDeviceNoContent() *PutEntropyDeviceNoContent { 60 | return &PutEntropyDeviceNoContent{} 61 | } 62 | 63 | /*PutEntropyDeviceNoContent handles this case with default header values. 64 | 65 | Entropy device created 66 | */ 67 | type PutEntropyDeviceNoContent struct { 68 | } 69 | 70 | func (o *PutEntropyDeviceNoContent) Error() string { 71 | return fmt.Sprintf("[PUT /entropy][%d] putEntropyDeviceNoContent ", 204) 72 | } 73 | 74 | func (o *PutEntropyDeviceNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 75 | 76 | return nil 77 | } 78 | 79 | // NewPutEntropyDeviceDefault creates a PutEntropyDeviceDefault with default headers values 80 | func NewPutEntropyDeviceDefault(code int) *PutEntropyDeviceDefault { 81 | return &PutEntropyDeviceDefault{ 82 | _statusCode: code, 83 | } 84 | } 85 | 86 | /*PutEntropyDeviceDefault handles this case with default header values. 87 | 88 | Internal server error 89 | */ 90 | type PutEntropyDeviceDefault struct { 91 | _statusCode int 92 | 93 | Payload *models.Error 94 | } 95 | 96 | // Code gets the status code for the put entropy device default response 97 | func (o *PutEntropyDeviceDefault) Code() int { 98 | return o._statusCode 99 | } 100 | 101 | func (o *PutEntropyDeviceDefault) Error() string { 102 | return fmt.Sprintf("[PUT /entropy][%d] putEntropyDevice default %+v", o._statusCode, o.Payload) 103 | } 104 | 105 | func (o *PutEntropyDeviceDefault) GetPayload() *models.Error { 106 | return o.Payload 107 | } 108 | 109 | func (o *PutEntropyDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 110 | 111 | o.Payload = new(models.Error) 112 | 113 | // response payload 114 | if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { 115 | return err 116 | } 117 | 118 | return nil 119 | } 120 | -------------------------------------------------------------------------------- /client_transports.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import ( 17 | "context" 18 | "github.com/go-openapi/runtime" 19 | "net" 20 | "net/http" 21 | 22 | httptransport "github.com/go-openapi/runtime/client" 23 | "github.com/sirupsen/logrus" 24 | 25 | "github.com/firecracker-microvm/firecracker-go-sdk/client" 26 | ) 27 | 28 | // NewUnixSocketTransport creates a new clientTransport configured at the specified Unix socketPath. 29 | func NewUnixSocketTransport(socketPath string, logger *logrus.Entry, debug bool) runtime.ClientTransport { 30 | socketTransport := &http.Transport{ 31 | DialContext: func(ctx context.Context, network, path string) (net.Conn, error) { 32 | addr, err := net.ResolveUnixAddr("unix", socketPath) 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | return net.DialUnix("unix", nil, addr) 38 | }, 39 | } 40 | 41 | transport := httptransport.New(client.DefaultHost, client.DefaultBasePath, client.DefaultSchemes) 42 | transport.Transport = socketTransport 43 | 44 | if debug { 45 | transport.SetDebug(debug) 46 | } 47 | 48 | if logger != nil { 49 | transport.SetLogger(logger) 50 | } 51 | 52 | return transport 53 | } 54 | -------------------------------------------------------------------------------- /client_transports_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import ( 17 | "context" 18 | "net" 19 | "net/http" 20 | "os" 21 | "testing" 22 | "time" 23 | 24 | "github.com/firecracker-microvm/firecracker-go-sdk/client/operations" 25 | "github.com/go-openapi/runtime" 26 | "github.com/stretchr/testify/assert" 27 | ) 28 | 29 | const expectedEndpointPath = "/test-operation" 30 | 31 | func TestNewUnixSocketTransport(t *testing.T) { 32 | done := make(chan bool) 33 | 34 | socketPath := "testingUnixSocket.sock" 35 | listener, err := net.Listen("unix", socketPath) 36 | if err != nil { 37 | panic(err) 38 | } 39 | 40 | server := http.Server{ 41 | Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 42 | assert.Equal(t, expectedEndpointPath, req.URL.String()) 43 | w.WriteHeader(http.StatusOK) 44 | close(done) 45 | }), 46 | } 47 | 48 | go server.Serve(listener) 49 | defer func() { 50 | server.Shutdown(context.Background()) 51 | listener.Close() 52 | os.Remove(socketPath) 53 | }() 54 | 55 | unixTransport := NewUnixSocketTransport(socketPath, nil, false) 56 | unixTransport.Submit(testOperation()) 57 | 58 | select { 59 | case <-time.After(100 * time.Millisecond): 60 | t.Errorf("Timed out from the listener") 61 | case <-done: 62 | } 63 | } 64 | 65 | func testOperation() *runtime.ClientOperation { 66 | return &runtime.ClientOperation{ 67 | ID: "putLogger", 68 | Method: "PUT", 69 | PathPattern: expectedEndpointPath, 70 | ProducesMediaTypes: []string{"application/json"}, 71 | Schemes: []string{"http"}, 72 | Params: operations.NewPutLoggerParams(), 73 | Reader: &operations.PutLoggerReader{}, 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /cni/internal/cniutil.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package internal 15 | 16 | import ( 17 | "fmt" 18 | 19 | current "github.com/containernetworking/cni/pkg/types/100" 20 | ) 21 | 22 | // InterfaceIPs returns the IPs associated with the interface possessing the provided name and 23 | // sandbox. 24 | func InterfaceIPs(result *current.Result, ifaceName string, sandbox string) []*current.IPConfig { 25 | var ifaceIPs []*current.IPConfig 26 | for _, ipconfig := range result.IPs { 27 | if ipconfig.Interface != nil { 28 | iface := result.Interfaces[*ipconfig.Interface] 29 | if iface.Name == ifaceName && iface.Sandbox == sandbox { 30 | ifaceIPs = append(ifaceIPs, ipconfig) 31 | } 32 | } 33 | } 34 | 35 | return ifaceIPs 36 | } 37 | 38 | // FilterBySandbox returns scans the provided list of interfaces and returns two lists: the first 39 | // are a list of interfaces with the provided sandboxID, the second are the other interfaces not 40 | // in that sandboxID. 41 | func FilterBySandbox( 42 | sandbox string, ifaces ...*current.Interface, 43 | ) (in []*current.Interface, out []*current.Interface) { 44 | for _, iface := range ifaces { 45 | if iface.Sandbox == sandbox { 46 | in = append(in, iface) 47 | } else { 48 | out = append(out, iface) 49 | } 50 | } 51 | 52 | return 53 | } 54 | 55 | // IfacesWithName scans the provided list of ifaces and returns the ones with the provided name 56 | func IfacesWithName(name string, ifaces ...*current.Interface) []*current.Interface { 57 | var foundIfaces []*current.Interface 58 | for _, iface := range ifaces { 59 | if iface.Name == name { 60 | foundIfaces = append(foundIfaces, iface) 61 | } 62 | } 63 | 64 | return foundIfaces 65 | } 66 | 67 | // VMTapPair takes a CNI result and returns the vm iface and the tap iface corresponding 68 | // to the provided vmID. See the vmconf package docs for details on the expected 69 | // vm and tap iface configurations. 70 | func VMTapPair( 71 | result *current.Result, 72 | vmID string, 73 | ) ( 74 | vmIface *current.Interface, 75 | tapIface *current.Interface, 76 | err error, 77 | ) { 78 | vmIfaces, otherIfaces := FilterBySandbox(vmID, result.Interfaces...) 79 | if len(vmIfaces) > 1 { 80 | return nil, nil, fmt.Errorf("expected to find at most 1 interface in sandbox %q, but instead found %d", 81 | vmID, len(vmIfaces)) 82 | } else if len(vmIfaces) == 0 { 83 | return nil, nil, LinkNotFoundError{device: fmt.Sprintf("pseudo-device for %s", vmID)} 84 | } 85 | 86 | vmIface = vmIfaces[0] 87 | 88 | // As specified in the package docstring, the vm interface is given the same name as the 89 | // corresponding tap device outside the VM. The tap device, however, will be in a sandbox 90 | // corresponding to a network namespace path. 91 | tapName := vmIface.Name 92 | 93 | tapIfaces := IfacesWithName(tapName, otherIfaces...) 94 | if len(tapIfaces) > 1 { 95 | return nil, nil, fmt.Errorf("expected to find at most 1 interface with name %q, but instead found %d", 96 | tapName, len(tapIfaces)) 97 | } else if len(tapIfaces) == 0 { 98 | return nil, nil, LinkNotFoundError{device: tapName} 99 | } 100 | 101 | tapIface = tapIfaces[0] 102 | 103 | return vmIface, tapIface, nil 104 | } 105 | -------------------------------------------------------------------------------- /cni/vmconf/vmconf_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package vmconf 15 | 16 | import ( 17 | "net" 18 | "testing" 19 | 20 | "github.com/containernetworking/cni/pkg/types" 21 | current "github.com/containernetworking/cni/pkg/types/100" 22 | "github.com/stretchr/testify/assert" 23 | "github.com/stretchr/testify/require" 24 | "github.com/vishvananda/netlink" 25 | 26 | "github.com/firecracker-microvm/firecracker-go-sdk/cni/internal" 27 | ) 28 | 29 | func TestMTUOf(t *testing.T) { 30 | netNS := internal.MockNetNS{MockPath: "/my/lil/netns"} 31 | 32 | redirectIfName := "veth0" 33 | redirectMTU := 1337 34 | redirectMac, err := net.ParseMAC("22:33:44:55:66:77") 35 | require.NoError(t, err, "failed to get redirect mac") 36 | 37 | tapName := "tap0" 38 | tapMTU := 1338 39 | tapMac, err := net.ParseMAC("11:22:33:44:55:66") 40 | require.NoError(t, err, "failed to get tap mac") 41 | 42 | nlOps := &internal.MockNetlinkOps{ 43 | CreatedTap: &internal.MockLink{ 44 | LinkAttrs: netlink.LinkAttrs{ 45 | Name: tapName, 46 | HardwareAddr: tapMac, 47 | MTU: tapMTU, 48 | }, 49 | }, 50 | RedirectIface: &internal.MockLink{ 51 | LinkAttrs: netlink.LinkAttrs{ 52 | Name: redirectIfName, 53 | HardwareAddr: redirectMac, 54 | MTU: redirectMTU, 55 | }, 56 | }, 57 | } 58 | 59 | actualMTU, err := mtuOf(tapName, netNS, nlOps) 60 | require.NoError(t, err, "failed to get mtu") 61 | assert.Equal(t, tapMTU, actualMTU, "received unexpected tap MTU") 62 | } 63 | 64 | func TestIPBootParams(t *testing.T) { 65 | staticNetworkConf := &StaticNetworkConf{ 66 | TapName: "taptaptap", 67 | NetNSPath: "/my/lil/netns", 68 | VMMacAddr: "00:11:22:33:44:55", 69 | VMIfName: "eth0", 70 | VMMTU: 1337, 71 | VMIPConfig: ¤t.IPConfig{ 72 | Address: net.IPNet{ 73 | IP: net.IPv4(10, 0, 0, 2), 74 | Mask: net.IPv4Mask(255, 255, 255, 0), 75 | }, 76 | Gateway: net.IPv4(10, 0, 0, 1), 77 | }, 78 | VMRoutes: []*types.Route{{ 79 | Dst: net.IPNet{ 80 | IP: net.IPv4(192, 168, 0, 2), 81 | Mask: net.IPv4Mask(255, 255, 0, 0), 82 | }, 83 | GW: net.IPv4(192, 168, 0, 1), 84 | }}, 85 | VMNameservers: []string{"1.1.1.1", "8.8.8.8", "1.0.0.1"}, 86 | VMDomain: "example.com", 87 | VMSearchDomains: []string{"look", "here"}, 88 | VMResolverOptions: []string{"choice", "is", "an", "illusion"}, 89 | } 90 | 91 | expectedIPBootParam := "10.0.0.2::10.0.0.1:255.255.255.0::eth0:off:1.1.1.1:8.8.8.8:" 92 | actualIPBootParam := staticNetworkConf.IPBootParam() 93 | assert.Equal(t, expectedIPBootParam, actualIPBootParam) 94 | } 95 | -------------------------------------------------------------------------------- /command_builder_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import ( 17 | "bytes" 18 | "context" 19 | "reflect" 20 | "testing" 21 | ) 22 | 23 | func TestVMCommandBuilder(t *testing.T) { 24 | t.Run("immutability", testVMCommandBuilderImmutable) 25 | t.Run("chaining", testVMCommandBuilderChaining) 26 | t.Run("build", testVMCommandBuilderBuild) 27 | } 28 | 29 | func testVMCommandBuilderImmutable(t *testing.T) { 30 | b := VMCommandBuilder{} 31 | b.WithSocketPath("foo"). 32 | WithArgs([]string{"baz", "qux"}). 33 | AddArgs("moo", "cow") 34 | 35 | if e, a := []string(nil), b.SocketPath(); !reflect.DeepEqual(e, a) { 36 | t.Errorf("expected immutable builder, but socket path was set: %q", a) 37 | } 38 | 39 | if e, a := ([]string)(nil), b.Args(); !reflect.DeepEqual(e, a) { 40 | t.Errorf("args should have been empty, but received %v", a) 41 | } 42 | } 43 | 44 | func testVMCommandBuilderChaining(t *testing.T) { 45 | b := VMCommandBuilder{}. 46 | WithSocketPath("socket-path"). 47 | WithBin("bin") 48 | 49 | if e, a := []string{"--api-sock", "socket-path"}, b.SocketPath(); !reflect.DeepEqual(e, a) { 50 | t.Errorf("expected %v, but received %v", e, a) 51 | } 52 | 53 | if e, a := "bin", b.Bin(); e != a { 54 | t.Errorf("expected %v, but received %v", e, a) 55 | } 56 | } 57 | 58 | func testVMCommandBuilderBuild(t *testing.T) { 59 | stdout := &bytes.Buffer{} 60 | stderr := &bytes.Buffer{} 61 | stdin := &bytes.Buffer{} 62 | 63 | ctx := context.Background() 64 | b := VMCommandBuilder{}. 65 | WithSocketPath("socket-path"). 66 | WithBin("bin"). 67 | WithStdout(stdout). 68 | WithStderr(stderr). 69 | WithStdin(stdin). 70 | WithArgs([]string{"foo"}). 71 | AddArgs("--bar", "baz") 72 | cmd := b.Build(ctx) 73 | 74 | expectedArgs := []string{ 75 | "bin", 76 | "--api-sock", 77 | "socket-path", 78 | "foo", 79 | "--bar", 80 | "baz", 81 | } 82 | 83 | if e, a := stdout, cmd.Stdout; !reflect.DeepEqual(e, a) { 84 | t.Errorf("expected stdout, %v, but received %v", e, a) 85 | } 86 | 87 | if e, a := stderr, cmd.Stderr; !reflect.DeepEqual(e, a) { 88 | t.Errorf("expected stderr, %v, but received %v", e, a) 89 | } 90 | 91 | if e, a := stdin, cmd.Stdin; !reflect.DeepEqual(e, a) { 92 | t.Errorf("expected stdin, %v, but received %v", e, a) 93 | } 94 | 95 | if e, a := expectedArgs, cmd.Args; !reflect.DeepEqual(e, a) { 96 | t.Errorf("expected %v, but received an invalid set of arguments %v", e, a) 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | /* 15 | Package firecracker provides a library to interact with the Firecracker API. 16 | 17 | Firecracker is an open-source virtualization technology that is purpose-built 18 | for creating and managing secure, multi-tenant containers and functions-based 19 | services. See https://firecracker-microvm.github.io/ for more details. 20 | 21 | This library requires Go 1.23 or later and can be used with Go modules. 22 | 23 | BUG(aws): There are some Firecracker features that are not yet supported by the 24 | SDK. These are tracked as GitHub issues with the firecracker-feature label: 25 | https://github.com/firecracker-microvm/firecracker-go-sdk/issues?q=is%3Aissue+is%3Aopen+label%3Afirecracker-feature 26 | 27 | This library is licensed under the Apache 2.0 License. 28 | */ 29 | package firecracker 30 | -------------------------------------------------------------------------------- /docs/snapshotting.md: -------------------------------------------------------------------------------- 1 | # Snapshotting 2 | 3 | Snapshotting is currently supported in the Firecracker Go SDK using Firecracker v1.0.0's API. 4 | 5 | Due to [known issues and limitations](https://github.com/firecracker-microvm/firecracker/blob/firecracker-v1.0/docs/snapshotting/snapshot-support.md#known-issues-and-limitations), it is currently not recommended to use snapshots in production. 6 | 7 | Snapshots created in this version only save the following: 8 | - guest memory 9 | - emulated hardware state (both KVM & Firecracker emulated hardware) 10 | 11 | Each of the above are saved in its own separate file. Anything else is up to the user to restore (tap devices, drives, etc.). 12 | 13 | In particular, drives must be in the same location as they were when loading the snapshot. Otherwise, the API call will fail. Changing said drive file can lead to some unexpected behaviors, so it is recommended to make minimal changes to the drive. 14 | 15 | Snapshots can only be loaded upon device startup. Upon loading the snapshot, the emulated hardware state is restored, and normal VM activites can resume right where they left off. 16 | 17 | Read more in-depth documentation on Firecracker's snapshotting tool [here](https://github.com/firecracker-microvm/firecracker/blob/firecracker-v1.0/docs/snapshotting/snapshot-support.md). 18 | 19 | ## Using Snapshots via Firecracker Go SDK 20 | 21 | Snapshots can be created via a machine object's `CreateSnapshot()` function. The call will make the snapshot files at the specified paths, with the memory saved to `memPath`, and the machine state saved to `snapPath`. The VM must be paused beforehand. 22 | 23 | ``` 24 | import ( 25 | sdk "github.com/firecracker-microvm/firecracker-go-sdk" 26 | ) 27 | 28 | ... 29 | 30 | ctx := context.Background() 31 | cfg := sdk.Config{ 32 | 33 | ... 34 | 35 | } 36 | 37 | m, _ := sdk.NewMachine(ctx, cfg) 38 | m.Start(ctx) 39 | m.PauseVM(ctx) 40 | m.CreateSnapshot(ctx, memPath, snapPath) 41 | ``` 42 | 43 | The snapshot can be loaded at any later time at creation of a machine via the machine's `NewMachine()` function, using `WithSnapshot()` as an option. Upon starting, the VM loads the snapshot and must then be resumed before attempting to use it. 44 | 45 | ``` 46 | ctx := context.Background() 47 | cfg := sdk.Config{ 48 | 49 | ... 50 | 51 | } 52 | m, _ := sdk.NewMachine(ctx, cfg, sdk.WithSnapshot(memPath, snapPath)) 53 | 54 | m.Start(ctx) 55 | m.ResumeVM(ctx) 56 | ``` 57 | 58 | Check out [examples/cmd/snapshotting](../examples/cmd/snapshotting) for a quick example that can be run on your machine. -------------------------------------------------------------------------------- /drives.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package firecracker 14 | 15 | import ( 16 | "strconv" 17 | 18 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 19 | ) 20 | 21 | const rootDriveName = "root_drive" 22 | 23 | // DrivesBuilder is a builder that will build an array of drives used to set up 24 | // the firecracker microVM. The DriveID will be an incrementing number starting 25 | // at one 26 | type DrivesBuilder struct { 27 | rootDrive models.Drive 28 | drives []models.Drive 29 | } 30 | 31 | // NewDrivesBuilder will return a new DrivesBuilder with a given rootfs. 32 | func NewDrivesBuilder(rootDrivePath string) DrivesBuilder { 33 | return DrivesBuilder{}.WithRootDrive(rootDrivePath) 34 | } 35 | 36 | // DriveOpt represents an optional function used to allow for specific 37 | // customization of the models.Drive structure. 38 | type DriveOpt func(*models.Drive) 39 | 40 | // WithRootDrive will set the given builder with the a new root path. The root 41 | // drive will be set to read and write by default. 42 | func (b DrivesBuilder) WithRootDrive(rootDrivePath string, opts ...DriveOpt) DrivesBuilder { 43 | b.rootDrive = models.Drive{ 44 | DriveID: String(rootDriveName), 45 | PathOnHost: &rootDrivePath, 46 | IsRootDevice: Bool(true), 47 | IsReadOnly: Bool(false), 48 | } 49 | 50 | for _, opt := range opts { 51 | opt(&b.rootDrive) 52 | } 53 | 54 | return b 55 | } 56 | 57 | // AddDrive will add a new drive to the given builder. 58 | func (b DrivesBuilder) AddDrive(path string, readOnly bool, opts ...DriveOpt) DrivesBuilder { 59 | drive := models.Drive{ 60 | DriveID: String(strconv.Itoa(len(b.drives))), 61 | PathOnHost: &path, 62 | IsRootDevice: Bool(false), 63 | IsReadOnly: &readOnly, 64 | } 65 | 66 | for _, opt := range opts { 67 | opt(&drive) 68 | } 69 | 70 | b.drives = append(b.drives, drive) 71 | return b 72 | } 73 | 74 | // Build will construct an array of drives with the root drive at the very end. 75 | func (b DrivesBuilder) Build() []models.Drive { 76 | return append(b.drives, b.rootDrive) 77 | } 78 | 79 | // WithDriveID sets the ID of the drive 80 | func WithDriveID(id string) DriveOpt { 81 | return func(d *models.Drive) { 82 | d.DriveID = String(id) 83 | } 84 | } 85 | 86 | // WithReadOnly sets the drive read-only 87 | func WithReadOnly(flag bool) DriveOpt { 88 | return func(d *models.Drive) { 89 | d.IsReadOnly = Bool(flag) 90 | } 91 | } 92 | 93 | // WithPartuuid sets the unique ID of the boot partition 94 | func WithPartuuid(uuid string) DriveOpt { 95 | return func(d *models.Drive) { 96 | d.Partuuid = uuid 97 | } 98 | } 99 | 100 | // WithRateLimiter sets the rate limitter of the drive 101 | func WithRateLimiter(limiter models.RateLimiter) DriveOpt { 102 | return func(d *models.Drive) { 103 | d.RateLimiter = &limiter 104 | } 105 | } 106 | 107 | // WithCacheType sets the cache strategy for the block device 108 | func WithCacheType(cacheType string) DriveOpt { 109 | return func(d *models.Drive) { 110 | d.CacheType = String(cacheType) 111 | } 112 | } 113 | 114 | // WithIoEngine sets the io engine of the drive 115 | // Defaults to Sync, Async is in developer preview at the moment 116 | // https://github.com/firecracker-microvm/firecracker/blob/v1.1.0/docs/api_requests/block-io-engine.md 117 | func WithIoEngine(ioEngine string) DriveOpt { 118 | return func(d *models.Drive) { 119 | d.IoEngine = String(ioEngine) 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /examples/cmd/snapshotting/.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | 3 | -------------------------------------------------------------------------------- /examples/cmd/snapshotting/.hack/go.mod: -------------------------------------------------------------------------------- 1 | // This is a fake go.mod 2 | // Older versions of go have different go get/go install semantics. In particular: 3 | // 1. `go get` with `GO111MODULES=off` will retrieve and and install a package, but you can't specify a version 4 | // 2. `go get` with `GO111MODULES=on` will retrive a packge at a specific version, but messes with the go.mod. The package can then be installed with `go install` 5 | 6 | // We don't actually want binary dependencies to modify the go.mod but since we want to pin versions, we create this unused go.mod 7 | // that `go get` can mess with without affecting our main codebase. 8 | module hack 9 | 10 | go 1.11 11 | 12 | require ( 13 | github.com/awslabs/tc-redirect-tap v0.0.0-20240408144842-496fddc89db6 // indirect 14 | github.com/containernetworking/plugins v1.1.1 // indirect 15 | ) 16 | -------------------------------------------------------------------------------- /examples/cmd/snapshotting/Makefile: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | # not use this file except in compliance with the License. A copy of the 5 | # License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | 14 | RELEASE_URL=https://github.com/firecracker-microvm/firecracker/releases 15 | VER=v1.4.1 16 | 17 | ARCH=$(shell uname -m) 18 | GID = $(shell id -g) 19 | 20 | PWD=$(shell pwd) 21 | GOBIN=$(PWD)/bin 22 | FC_TEST_DATA_PATH?=$(PWD) 23 | 24 | # --location is needed to follow redirects on github.com 25 | curl = curl --location 26 | 27 | GO_VERSION = $(shell go version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f1,2) 28 | ifeq ($(GO_VERSION), $(filter $(GO_VERSION),1.14 1.15)) 29 | define install_go 30 | cd .hack; GO111MODULE=on GOBIN=$(GOBIN) go get $(1)@$(2) 31 | cd .hack; GO111MODULE=on GOBIN=$(GOBIN) go install $(1) 32 | endef 33 | else 34 | define install_go 35 | GOBIN=$(GOBIN) go install $(1)@$(2) 36 | endef 37 | endif 38 | 39 | all: snapshot-example plugins root-drive-with-ssh.img root-drive-ssh-key vmlinux firecracker 40 | 41 | plugins: bin/tc-redirect-tap bin/ptp bin/host-local | bin 42 | 43 | bin: 44 | mkdir -p bin 45 | 46 | bin/tc-redirect-tap: bin 47 | $(call install_go,github.com/awslabs/tc-redirect-tap/cmd/tc-redirect-tap,v0.0.0-20240408144842-496fddc89db6) 48 | 49 | bin/ptp: bin 50 | $(call install_go,github.com/containernetworking/plugins/plugins/main/ptp,v1.1.1) 51 | 52 | bin/host-local: bin 53 | $(call install_go,github.com/containernetworking/plugins/plugins/ipam/host-local,v1.1.1) 54 | 55 | vmlinux: 56 | $(curl) -o vmlinux https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/${ARCH}/kernels/vmlinux.bin 57 | 58 | firecracker: 59 | $(curl) ${RELEASE_URL}/download/${VER}/firecracker-${VER}-${ARCH}.tgz | tar -xz 60 | mv release-${VER}-${ARCH}/firecracker-${VER}-${ARCH} firecracker 61 | rm -rf release-${VER}-${ARCH} 62 | 63 | # Use rootfs and ssh key pre-built from S3 following firecracker getting-started guide 64 | # https://github.com/firecracker-microvm/firecracker/blob/main/docs/getting-started.md 65 | # TODO: Change the pre-built rootfs to ubuntu 22.04 once firecracker team has that in the public S3 bucket 66 | # Currently the S3 bucket only has ubuntu 18.04 image 67 | root-drive-with-ssh.img root-drive-ssh-key: 68 | $(curl) -o root-drive-with-ssh.img https://s3.amazonaws.com/spec.ccfc.min/ci-artifacts/disks/${ARCH}/ubuntu-18.04.ext4 69 | $(curl) -o root-drive-ssh-key https://s3.amazonaws.com/spec.ccfc.min/ci-artifacts/disks/${ARCH}/ubuntu-18.04.id_rsa 70 | 71 | 72 | snapshot-example: 73 | go build -o $@ 74 | 75 | run: snapshot-example 76 | ./snapshot-example 77 | 78 | clean: 79 | rm -rf bin firecracker root-drive-ssh-key root-drive-with-ssh.img snapshot-example vmlinux 80 | 81 | .PHONY: all clean plugins run 82 | -------------------------------------------------------------------------------- /examples/cmd/snapshotting/README.md: -------------------------------------------------------------------------------- 1 | # Snapshotting demo 2 | 3 | This example shows snapshotting in action by sending a marker to a VM via a running process (in this case `sleep 422`), snapshotting the VM, closing it, loading and starting a new machine via the same snapshot, and checking for the marker. 4 | 5 | This test requires both KVM and root access. 6 | 7 | ## Running the test 8 | 9 | Run this test by first running 10 | 11 | ``` 12 | make all 13 | ``` 14 | 15 | followed by 16 | 17 | ``` 18 | sudo -E env PATH=$PATH go run example_demo.go 19 | ``` 20 | 21 | or, 22 | ``` 23 | sudo -E env PATH=$PATH make run 24 | ``` 25 | 26 | Note the user PATH variable is different from the root user's PATH variable, hence the need for `-E env PATH=$PATH`. 27 | 28 | Upon running, the VM logs will be printed to the console, as well as the IP of the VM. It will then show that it is sending the marker (in our case, `sleep 422`). 29 | 30 | Afterwards, the snapshot is created and the machine is terminated. The snapshot files are saved in the snapshotssh folder created in the directory. 31 | 32 | Then, a new machine is created, booted with the snapshot that was just taken, and the IP of the VM will once again be printed to the console (which should be the same as the last machine). The output of searching for the marker (in our case `ps -aux | grep "sleep 422"`) is then printed to the console and the user can confirm that the snapshot loaded properly. 33 | 34 | To run this test more dynamically, you can pause the execution of the program after starting the machine (i.e. after the call to m.Start() and the IP is shown on the screen). 35 | 36 | ``` 37 | err = m.Start() 38 | 39 | ... 40 | 41 | vmIP := m.Cfg.NetworkInterfaces[0].StaticConfiguration.IPConfiguration.IPAddr.IP.String() 42 | fmt.Printf("IP of VM: %v\n", vmIP) 43 | fmt.Scanln() // block, allows you to ssh from another shell 44 | 45 | ... 46 | 47 | err = m.Start() 48 | 49 | ... 50 | 51 | fmt.Println("Snapshot loaded") 52 | fmt.Printf("IP of VM: %v\n", ipToRestore) 53 | fmt.Scanln() // block, allows you to ssh from another shell 54 | ``` 55 | 56 | ``` 57 | sudo ssh -i root-drive-ssh-key root@[ip] 58 | ``` 59 | 60 | Pressing enter resumes execution of the program. 61 | 62 | You can remove dependencies via a simple `make clean`. 63 | 64 | ``` 65 | make clean 66 | ``` -------------------------------------------------------------------------------- /examples/cmd/snapshotting/go.mod: -------------------------------------------------------------------------------- 1 | module main 2 | 3 | go 1.23.0 4 | 5 | require ( 6 | github.com/firecracker-microvm/firecracker-go-sdk v1.0.0 7 | golang.org/x/crypto v0.38.0 8 | golang.org/x/sys v0.33.0 9 | ) 10 | 11 | require ( 12 | github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect 13 | github.com/containerd/fifo v1.1.0 // indirect 14 | github.com/containernetworking/cni v1.3.0 // indirect 15 | github.com/containernetworking/plugins v1.7.1 // indirect 16 | github.com/go-openapi/analysis v0.23.0 // indirect 17 | github.com/go-openapi/errors v0.22.1 // indirect 18 | github.com/go-openapi/jsonpointer v0.21.0 // indirect 19 | github.com/go-openapi/jsonreference v0.21.0 // indirect 20 | github.com/go-openapi/loads v0.22.0 // indirect 21 | github.com/go-openapi/runtime v0.24.1 // indirect 22 | github.com/go-openapi/spec v0.21.0 // indirect 23 | github.com/go-openapi/strfmt v0.23.0 // indirect 24 | github.com/go-openapi/swag v0.23.0 // indirect 25 | github.com/go-openapi/validate v0.24.0 // indirect 26 | github.com/google/uuid v1.6.0 // indirect 27 | github.com/hashicorp/errwrap v1.1.0 // indirect 28 | github.com/hashicorp/go-multierror v1.1.1 // indirect 29 | github.com/josharian/intern v1.0.0 // indirect 30 | github.com/mailru/easyjson v0.7.7 // indirect 31 | github.com/mitchellh/mapstructure v1.5.0 // indirect 32 | github.com/oklog/ulid v1.3.1 // indirect 33 | github.com/opentracing/opentracing-go v1.2.0 // indirect 34 | github.com/sirupsen/logrus v1.9.3 // indirect 35 | github.com/vishvananda/netlink v1.3.1-0.20250303224720-0e7078ed04c8 // indirect 36 | github.com/vishvananda/netns v0.0.5 // indirect 37 | go.mongodb.org/mongo-driver v1.14.0 // indirect 38 | gopkg.in/yaml.v2 v2.4.0 // indirect 39 | gopkg.in/yaml.v3 v3.0.1 // indirect 40 | ) 41 | 42 | replace github.com/firecracker-microvm/firecracker-go-sdk => ../../.. 43 | -------------------------------------------------------------------------------- /fctesting/test_writer.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package fctesting 14 | 15 | // TestWriter is used to mock out writing and/or do other things such as 16 | // syncing when to do assertions in the event that a writer is used in a 17 | // goroutine 18 | type TestWriter struct { 19 | WriteFn func([]byte) (int, error) 20 | } 21 | 22 | func (w *TestWriter) Write(b []byte) (int, error) { 23 | return w.WriteFn(b) 24 | } 25 | -------------------------------------------------------------------------------- /fctesting/utils.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package fctesting 15 | 16 | import ( 17 | "fmt" 18 | "os" 19 | "os/user" 20 | "testing" 21 | 22 | "golang.org/x/sys/unix" 23 | 24 | log "github.com/sirupsen/logrus" 25 | ) 26 | 27 | const rootDisableEnvName = "DISABLE_ROOT_TESTS" 28 | const logLevelEnvName = "FC_TEST_LOG_LEVEL" 29 | 30 | var rootDisabled bool 31 | 32 | func init() { 33 | if v := os.Getenv(rootDisableEnvName); len(v) != 0 { 34 | rootDisabled = true 35 | } 36 | } 37 | 38 | func RequiresKVM(t testing.TB) { 39 | accessErr := unix.Access("/dev/kvm", unix.W_OK) 40 | if accessErr != nil { 41 | var name string 42 | u, err := user.Current() 43 | if err == nil { 44 | name = u.Name 45 | } 46 | 47 | // On GitHub Actions, user.Current() doesn't return an error, but the name is "". 48 | if name == "" { 49 | name = fmt.Sprintf("uid=%d", os.Getuid()) 50 | } 51 | t.Skipf("/dev/kvm is not writable from %s: %s", name, accessErr) 52 | } 53 | } 54 | 55 | // RequiresRoot will ensure that tests that require root access are actually 56 | // root. In addition, this will skip root tests if the DISABLE_ROOT_TESTS is 57 | // set to true 58 | func RequiresRoot(t testing.TB) { 59 | if rootDisabled { 60 | t.Skip("skipping test that requires root") 61 | } 62 | 63 | if e, a := 0, os.Getuid(); e != a { 64 | t.Fatalf("This test must be run as root. "+ 65 | "To disable tests that require root, "+ 66 | "run the tests with the %s environment variable set.", 67 | rootDisableEnvName) 68 | } 69 | } 70 | 71 | func newLogger(t testing.TB) *log.Logger { 72 | str := os.Getenv(logLevelEnvName) 73 | l := log.New() 74 | if str == "" { 75 | return l 76 | } 77 | 78 | logLevel, err := log.ParseLevel(str) 79 | if err != nil { 80 | t.Fatalf("Failed to parse %q as Log Level: %v", str, err) 81 | } 82 | 83 | l.SetLevel(logLevel) 84 | return l 85 | } 86 | 87 | // NewLogEntry creates log.Entry. The level is specified by "FC_TEST_LOG_LEVEL" environment variable 88 | func NewLogEntry(t testing.TB) *log.Entry { 89 | return log.NewEntry(newLogger(t)) 90 | } 91 | -------------------------------------------------------------------------------- /fctesting/utils_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package fctesting 14 | 15 | import ( 16 | "os" 17 | "testing" 18 | ) 19 | 20 | func TestLoggingPanic(t *testing.T) { 21 | defer func() { 22 | if r := recover(); r != nil { 23 | t.Error(r) 24 | } 25 | }() 26 | 27 | os.Setenv("FC_TEST_LOG_LEVEL", "debug") 28 | l := NewLogEntry(t) 29 | l.Debug("TestLoggingPanic") 30 | } 31 | -------------------------------------------------------------------------------- /firecracker_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package firecracker 14 | 15 | import ( 16 | "context" 17 | "path/filepath" 18 | "testing" 19 | "time" 20 | 21 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 22 | "github.com/firecracker-microvm/firecracker-go-sdk/fctesting" 23 | "github.com/stretchr/testify/require" 24 | ) 25 | 26 | func TestClient(t *testing.T) { 27 | if testing.Short() { 28 | t.Skip() 29 | } 30 | 31 | ctx := context.Background() 32 | socketpath, cleanup := makeSocketPath(t) 33 | defer cleanup() 34 | 35 | cmd := VMCommandBuilder{}. 36 | WithBin(getFirecrackerBinaryPath()). 37 | WithSocketPath(socketpath). 38 | Build(ctx) 39 | 40 | if err := cmd.Start(); err != nil { 41 | t.Fatalf("failed to start firecracker vmm: %v", err) 42 | } 43 | 44 | defer func() { 45 | if err := cmd.Process.Kill(); err != nil { 46 | t.Errorf("failed to kill process: %v", err) 47 | } 48 | }() 49 | 50 | drive := &models.Drive{ 51 | DriveID: String("test"), 52 | IsReadOnly: Bool(false), 53 | IsRootDevice: Bool(false), 54 | PathOnHost: String(filepath.Join(testDataPath, "drive-2.img")), 55 | } 56 | 57 | client := NewClient(socketpath, fctesting.NewLogEntry(t), true) 58 | deadlineCtx, deadlineCancel := context.WithTimeout(ctx, 250*time.Millisecond) 59 | defer deadlineCancel() 60 | if err := waitForAliveVMM(deadlineCtx, client); err != nil { 61 | t.Fatal(err) 62 | } 63 | 64 | if _, err := client.PutGuestDriveByID(ctx, "test", drive); err != nil { 65 | t.Errorf("unexpected error on PutGuestDriveByID, %v", err) 66 | } 67 | } 68 | 69 | func TestGetFirecrackerVersion(t *testing.T) { 70 | if testing.Short() { 71 | t.Skip() 72 | } 73 | 74 | ctx := context.Background() 75 | socketpath, cleanup := makeSocketPath(t) 76 | defer cleanup() 77 | 78 | cmd := VMCommandBuilder{}. 79 | WithBin(getFirecrackerBinaryPath()). 80 | WithSocketPath(socketpath). 81 | Build(ctx) 82 | 83 | if err := cmd.Start(); err != nil { 84 | t.Fatalf("failed to start firecracker vmm: %v", err) 85 | } 86 | 87 | defer func() { 88 | if err := cmd.Process.Kill(); err != nil { 89 | t.Errorf("failed to kill process: %v", err) 90 | } 91 | }() 92 | 93 | client := NewClient(socketpath, fctesting.NewLogEntry(t), true) 94 | deadlineCtx, deadlineCancel := context.WithTimeout(ctx, 250*time.Millisecond) 95 | defer deadlineCancel() 96 | if err := waitForAliveVMM(deadlineCtx, client); err != nil { 97 | t.Fatal(err) 98 | } 99 | 100 | _, err := client.GetFirecrackerVersion(ctx) 101 | require.NoError(t, err, "failed to get firecracker version") 102 | } 103 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/firecracker-microvm/firecracker-go-sdk 2 | 3 | go 1.23.0 4 | 5 | require ( 6 | github.com/containerd/fifo v1.1.0 7 | github.com/containernetworking/cni v1.3.0 8 | github.com/containernetworking/plugins v1.7.1 9 | github.com/go-openapi/errors v0.22.1 10 | github.com/go-openapi/runtime v0.24.0 11 | github.com/go-openapi/strfmt v0.23.0 12 | github.com/go-openapi/swag v0.23.0 13 | github.com/go-openapi/validate v0.24.0 14 | github.com/go-ping/ping v1.2.0 15 | github.com/google/uuid v1.6.0 16 | github.com/hashicorp/go-multierror v1.1.1 17 | github.com/mdlayher/vsock v1.2.1 18 | github.com/sirupsen/logrus v1.9.3 19 | github.com/stretchr/testify v1.10.0 20 | github.com/vishvananda/netlink v1.3.1-0.20250303224720-0e7078ed04c8 21 | github.com/vishvananda/netns v0.0.5 22 | golang.org/x/crypto v0.38.0 23 | golang.org/x/sys v0.33.0 24 | ) 25 | 26 | require ( 27 | github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect 28 | github.com/davecgh/go-spew v1.1.1 // indirect 29 | github.com/go-openapi/analysis v0.23.0 // indirect 30 | github.com/go-openapi/jsonpointer v0.21.0 // indirect 31 | github.com/go-openapi/jsonreference v0.21.0 // indirect 32 | github.com/go-openapi/loads v0.22.0 // indirect 33 | github.com/go-openapi/spec v0.21.0 // indirect 34 | github.com/hashicorp/errwrap v1.0.0 // indirect 35 | github.com/josharian/intern v1.0.0 // indirect 36 | github.com/mailru/easyjson v0.7.7 // indirect 37 | github.com/mdlayher/socket v0.5.1 // indirect 38 | github.com/mitchellh/mapstructure v1.5.0 // indirect 39 | github.com/oklog/ulid v1.3.1 // indirect 40 | github.com/opentracing/opentracing-go v1.2.0 // indirect 41 | github.com/pmezard/go-difflib v1.0.0 // indirect 42 | go.mongodb.org/mongo-driver v1.14.0 // indirect 43 | golang.org/x/net v0.38.0 // indirect 44 | golang.org/x/sync v0.12.0 // indirect 45 | gopkg.in/yaml.v2 v2.4.0 // indirect 46 | gopkg.in/yaml.v3 v3.0.1 // indirect 47 | ) 48 | -------------------------------------------------------------------------------- /go_swagger_layout.yaml: -------------------------------------------------------------------------------- 1 | layout: 2 | application: 3 | - name: mockClient 4 | source: asset:mockclient 5 | target: "{{ joinFilePath .Target .ClientPackage }}" 6 | file_name: "{{ .Name }}_mock_client.go" 7 | -------------------------------------------------------------------------------- /internal/cpu_template.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package internal 15 | 16 | import ( 17 | "bufio" 18 | "io" 19 | "os" 20 | "regexp" 21 | "runtime" 22 | "sync" 23 | ) 24 | 25 | var ( 26 | isIntel bool 27 | isIntelOnce sync.Once 28 | ) 29 | 30 | // SupportCPUTemplate returns true if Firecracker supports CPU templates on 31 | // the current architecture. 32 | func SupportCPUTemplate() (bool, error) { 33 | if runtime.GOARCH != "amd64" { 34 | return false, nil 35 | } 36 | 37 | var err error 38 | isIntelOnce.Do(func() { 39 | isIntel, err = checkIsIntel() 40 | }) 41 | return isIntel, err 42 | } 43 | 44 | var vendorID = regexp.MustCompile(`^vendor_id\s*:\s*(.+)$`) 45 | 46 | func checkIsIntel() (bool, error) { 47 | f, err := os.Open("/proc/cpuinfo") 48 | if err != nil { 49 | return false, err 50 | } 51 | defer f.Close() 52 | 53 | id, err := findFirstVendorID(f) 54 | if err != nil { 55 | return false, err 56 | } 57 | 58 | return id == "GenuineIntel", nil 59 | } 60 | 61 | func findFirstVendorID(r io.Reader) (string, error) { 62 | s := bufio.NewScanner(r) 63 | for s.Scan() { 64 | line := s.Text() 65 | matches := vendorID.FindStringSubmatch(line) 66 | if len(matches) == 2 { 67 | return matches[1], nil 68 | } 69 | } 70 | return "", nil 71 | } -------------------------------------------------------------------------------- /internal/cpu_template_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package internal 15 | 16 | import ( 17 | "strings" 18 | "testing" 19 | 20 | "github.com/stretchr/testify/assert" 21 | "github.com/stretchr/testify/require" 22 | ) 23 | 24 | func TestFindFirstVendorID(t *testing.T) { 25 | cases := []struct { 26 | input string 27 | vendorID string 28 | }{ 29 | {"vendor_id : GenuineIntel", "GenuineIntel"}, 30 | {"vendor_id : AuthenticAMD", "AuthenticAMD"}, 31 | 32 | // aarch64 doesn't have vendor IDs. 33 | {"", ""}, 34 | } 35 | for _, c := range cases { 36 | r := strings.NewReader(c.input) 37 | id, err := findFirstVendorID(r) 38 | require.NoError(t, err) 39 | assert.Equal(t, c.vendorID, id) 40 | } 41 | } -------------------------------------------------------------------------------- /kernelargs.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import "strings" 17 | 18 | // kernelArgs serializes+deserializes kernel boot parameters from/into a map. 19 | // Kernel docs: https://www.kernel.org/doc/Documentation/admin-guide/kernel-parameters.txt 20 | // 21 | // "key=value" will result in map["key"] = &"value" 22 | // "key=" will result in map["key"] = &"" 23 | // "key" will result in map["key"] = nil 24 | type kernelArgs map[string]*string 25 | 26 | // serialize the kernelArgs back to a string that can be provided 27 | // to the kernel 28 | func (kargs kernelArgs) String() string { 29 | var fields []string 30 | for key, value := range kargs { 31 | field := key 32 | if value != nil { 33 | field += "=" + *value 34 | } 35 | fields = append(fields, field) 36 | } 37 | return strings.Join(fields, " ") 38 | } 39 | 40 | // deserialize the provided string to a kernelArgs map 41 | func parseKernelArgs(rawString string) kernelArgs { 42 | argMap := make(map[string]*string) 43 | for _, kv := range strings.Fields(rawString) { 44 | // only split into up to 2 fields (before and after the first "=") 45 | kvSplit := strings.SplitN(kv, "=", 2) 46 | 47 | key := kvSplit[0] 48 | 49 | var value *string 50 | if len(kvSplit) == 2 { 51 | value = &kvSplit[1] 52 | } 53 | 54 | argMap[key] = value 55 | } 56 | 57 | return argMap 58 | } 59 | -------------------------------------------------------------------------------- /kernelargs_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import ( 17 | "fmt" 18 | "testing" 19 | 20 | "github.com/stretchr/testify/require" 21 | ) 22 | 23 | func TestKernelArgsSerder(t *testing.T) { 24 | fooVal := "bar" 25 | booVal := "far" 26 | dooVal := "a=silly=val" 27 | emptyVal := "" 28 | 29 | argsString := fmt.Sprintf("foo=%s blah doo=%s huh=%s bleh duh=%s boo=%s", 30 | fooVal, 31 | dooVal, 32 | emptyVal, 33 | emptyVal, 34 | booVal, 35 | ) 36 | 37 | expectedParsedArgs := kernelArgs(map[string]*string{ 38 | "foo": &fooVal, 39 | "doo": &dooVal, 40 | "blah": nil, 41 | "huh": &emptyVal, 42 | "bleh": nil, 43 | "duh": &emptyVal, 44 | "boo": &booVal, 45 | }) 46 | 47 | actualParsedArgs := parseKernelArgs(argsString) 48 | require.Equal(t, expectedParsedArgs, actualParsedArgs, "kernel args parsed to unexpected values") 49 | 50 | reparsedArgs := parseKernelArgs(actualParsedArgs.String()) 51 | require.Equal(t, expectedParsedArgs, reparsedArgs, "serializing and deserializing kernel args did not result in same value") 52 | } 53 | -------------------------------------------------------------------------------- /machineiface.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import ( 17 | "context" 18 | ) 19 | 20 | // This ensures the interface method signatures match that of Machine 21 | var _ MachineIface = (*Machine)(nil) 22 | 23 | // MachineIface can be used for mocking and testing of the Machine. The Machine 24 | // is subject to change, meaning this interface would change. 25 | type MachineIface interface { 26 | Start(context.Context) error 27 | StopVMM() error 28 | Shutdown(context.Context) error 29 | Wait(context.Context) error 30 | SetMetadata(context.Context, interface{}) error 31 | UpdateGuestDrive(context.Context, string, string, ...PatchGuestDriveByIDOpt) error 32 | UpdateGuestNetworkInterfaceRateLimit(context.Context, string, RateLimiterSet, ...PatchGuestNetworkInterfaceByIDOpt) error 33 | } 34 | -------------------------------------------------------------------------------- /opts.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import ( 17 | "os/exec" 18 | 19 | "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 20 | "github.com/sirupsen/logrus" 21 | ) 22 | 23 | // Opt represents a functional option to help modify functionality of a Machine. 24 | type Opt func(*Machine) 25 | 26 | // WithClient will use the client in place rather than the client constructed 27 | // during bootstrapping of the machine. This option is useful for mocking out 28 | // tests. 29 | func WithClient(client *Client) Opt { 30 | return func(machine *Machine) { 31 | machine.client = client 32 | } 33 | } 34 | 35 | // WithLogger will allow for the Machine to use the provided logger. 36 | func WithLogger(logger *logrus.Entry) Opt { 37 | return func(machine *Machine) { 38 | machine.logger = logger 39 | } 40 | } 41 | 42 | // WithProcessRunner will allow for a specific command to be run instead of the 43 | // default firecracker command. 44 | // For example, this could be used to instead call the jailer instead of 45 | // firecracker directly. 46 | func WithProcessRunner(cmd *exec.Cmd) Opt { 47 | return func(machine *Machine) { 48 | machine.cmd = cmd 49 | } 50 | } 51 | 52 | // WithSnapshotOpt allows configuration of the snapshot config 53 | // to be passed to LoadSnapshot 54 | type WithSnapshotOpt func(*SnapshotConfig) 55 | 56 | // WithSnapshot will allow for the machine to start using a given snapshot. 57 | // 58 | // If using the UFFD memory backend, the memFilePath may be empty (it is 59 | // ignored), and instead the UFFD socket should be specified using 60 | // MemoryBackendType, as in the following example: 61 | // 62 | // WithSnapshot( 63 | // "", snapshotPath, 64 | // WithMemoryBackend(models.MemoryBackendBackendTypeUffd, "uffd.sock")) 65 | func WithSnapshot(memFilePath, snapshotPath string, opts ...WithSnapshotOpt) Opt { 66 | return func(m *Machine) { 67 | m.Cfg.Snapshot.MemFilePath = memFilePath 68 | m.Cfg.Snapshot.SnapshotPath = snapshotPath 69 | 70 | for _, opt := range opts { 71 | opt(&m.Cfg.Snapshot) 72 | } 73 | 74 | m.Handlers.Validation = m.Handlers.Validation.Remove(ValidateCfgHandlerName).Append(LoadSnapshotConfigValidationHandler) 75 | m.Handlers.FcInit = modifyHandlersForLoadSnapshot(m.Handlers.FcInit) 76 | } 77 | } 78 | 79 | func modifyHandlersForLoadSnapshot(l HandlerList) HandlerList { 80 | for _, h := range loadSnapshotRemoveHandlerList { 81 | l = l.Remove(h.Name) 82 | } 83 | l = l.Append(LoadSnapshotHandler) 84 | return l 85 | } 86 | 87 | // WithMemoryBackend sets the memory backend to the given type, using the given 88 | // backing file path (a regular file for "File" type, or a UFFD socket path for 89 | // "Uffd" type). 90 | // 91 | // Note that if MemFilePath is already configured for the snapshot config, it 92 | // will be ignored, and the backendPath specified here will be used instead. 93 | func WithMemoryBackend(backendType, backendPath string) WithSnapshotOpt { 94 | return func(cfg *SnapshotConfig) { 95 | cfg.MemBackend = &models.MemoryBackend{ 96 | BackendType: String(backendType), 97 | BackendPath: String(backendPath), 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /pointer_helpers.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package firecracker 14 | 15 | // BoolValue will return a boolean value. If the pointer is nil, then false 16 | // will be returned. 17 | func BoolValue(b *bool) bool { 18 | if b == nil { 19 | return false 20 | } 21 | 22 | return *b 23 | } 24 | 25 | // Bool will return a pointer value of the given parameter. 26 | func Bool(b bool) *bool { 27 | return &b 28 | } 29 | 30 | // StringValue will return a string value. If the pointer is nil, then an empty 31 | // string will be returned. 32 | func StringValue(str *string) string { 33 | if str == nil { 34 | return "" 35 | } 36 | 37 | return *str 38 | } 39 | 40 | // String will return a pointer value of the given parameter. 41 | func String(str string) *string { 42 | return &str 43 | } 44 | 45 | // Int64 will return a pointer value of the given parameter. 46 | func Int64(v int64) *int64 { 47 | return &v 48 | } 49 | 50 | // Int64Value will return an int64 value. If the pointer is nil, then zero will 51 | // be returned. 52 | func Int64Value(v *int64) int64 { 53 | if v == nil { 54 | return 0 55 | } 56 | 57 | return *v 58 | } 59 | 60 | // IntValue will return an int value. If the pointer is nil, zero will be 61 | // returned. 62 | func IntValue(v *int) int { 63 | if v == nil { 64 | return 0 65 | } 66 | 67 | return *v 68 | } 69 | 70 | // Int will return a pointer value of the given parameters. 71 | func Int(v int) *int { 72 | return &v 73 | } 74 | -------------------------------------------------------------------------------- /rate_limiter.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import ( 17 | "time" 18 | 19 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 20 | ) 21 | 22 | // RateLimiterOpt represents a functional option for rate limiting construction 23 | type RateLimiterOpt func(*models.RateLimiter) 24 | 25 | // NewRateLimiter will construct a new RateLimiter with given parameters. 26 | func NewRateLimiter(bandwidth, ops models.TokenBucket, opts ...RateLimiterOpt) *models.RateLimiter { 27 | limiter := &models.RateLimiter{ 28 | Bandwidth: &bandwidth, 29 | Ops: &ops, 30 | } 31 | 32 | for _, opt := range opts { 33 | opt(limiter) 34 | } 35 | 36 | return limiter 37 | } 38 | 39 | // TokenBucketBuilder is a builder that allows of building components of the 40 | // models.RateLimiter structure. 41 | type TokenBucketBuilder struct { 42 | bucket models.TokenBucket 43 | } 44 | 45 | // WithBucketSize will set the bucket size for the given token bucket 46 | func (b TokenBucketBuilder) WithBucketSize(size int64) TokenBucketBuilder { 47 | b.bucket.Size = &size 48 | 49 | return b 50 | } 51 | 52 | // WithRefillDuration will set the given refill duration of the bucket fill rate. 53 | func (b TokenBucketBuilder) WithRefillDuration(dur time.Duration) TokenBucketBuilder { 54 | ms := dur.Nanoseconds() 55 | ms /= int64(time.Millisecond) 56 | b.bucket.RefillTime = &ms 57 | 58 | return b 59 | } 60 | 61 | // WithInitialSize will set the initial token bucket size 62 | func (b TokenBucketBuilder) WithInitialSize(size int64) TokenBucketBuilder { 63 | b.bucket.OneTimeBurst = &size 64 | 65 | return b 66 | } 67 | 68 | // Build will return a new token bucket 69 | func (b TokenBucketBuilder) Build() models.TokenBucket { 70 | return b.bucket 71 | } 72 | -------------------------------------------------------------------------------- /rate_limiter_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker_test 15 | 16 | import ( 17 | "testing" 18 | "time" 19 | 20 | "github.com/firecracker-microvm/firecracker-go-sdk" 21 | models "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 22 | "github.com/stretchr/testify/assert" 23 | ) 24 | 25 | func TestRateLimiter(t *testing.T) { 26 | bucket := firecracker.TokenBucketBuilder{}. 27 | WithRefillDuration(1 * time.Hour). 28 | WithBucketSize(100). 29 | WithInitialSize(100). 30 | Build() 31 | 32 | expectedBucket := models.TokenBucket{ 33 | OneTimeBurst: firecracker.Int64(100), 34 | RefillTime: firecracker.Int64(3600000), 35 | Size: firecracker.Int64(100), 36 | } 37 | 38 | assert.Equal(t, expectedBucket, bucket) 39 | } 40 | 41 | func TestRateLimiter_RefillTime(t *testing.T) { 42 | cases := []struct { 43 | Name string 44 | Dur time.Duration 45 | ExpectedMilliseconds int64 46 | }{ 47 | { 48 | Name: "one hour", 49 | Dur: 1 * time.Hour, 50 | ExpectedMilliseconds: 3600000, 51 | }, 52 | { 53 | Name: "zero", 54 | ExpectedMilliseconds: 0, 55 | }, 56 | } 57 | 58 | for _, c := range cases { 59 | t.Run(c.Name, func(t *testing.T) { 60 | bucket := firecracker.TokenBucketBuilder{}. 61 | WithRefillDuration(c.Dur). 62 | Build() 63 | 64 | assert.Equal(t, &c.ExpectedMilliseconds, bucket.RefillTime) 65 | }) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /snapshot.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | import "github.com/firecracker-microvm/firecracker-go-sdk/client/models" 17 | 18 | type SnapshotConfig struct { 19 | MemFilePath string 20 | MemBackend *models.MemoryBackend 21 | SnapshotPath string 22 | EnableDiffSnapshots bool 23 | ResumeVM bool 24 | } 25 | 26 | // GetMemBackendPath returns the effective memory backend path. If MemBackend 27 | // is not set, then MemFilePath from SnapshotConfig will be returned. 28 | func (cfg *SnapshotConfig) GetMemBackendPath() string { 29 | if cfg.MemBackend != nil && cfg.MemBackend.BackendPath != nil { 30 | return *cfg.MemBackend.BackendPath 31 | } 32 | return cfg.MemFilePath 33 | } 34 | -------------------------------------------------------------------------------- /swagger.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | //go:generate find ./client ! -name swagger.yaml -type f -delete 15 | 16 | // --skip-validation is used in the command-lines below to remove the network dependency that the swagger generator has 17 | // in attempting to validate that the email address specified in the yaml file is valid. 18 | 19 | //go:generate docker run --add-host github.com:127.1.1.1 --rm --net=none -v $PWD:/work -w /work quay.io/goswagger/swagger:v0.20.1 generate model -f ./client/swagger.yaml -T ./templates --model-package=client/models --client-package=client --copyright-file=COPYRIGHT_HEADER --skip-validation 20 | //go:generate docker run --add-host github.com:127.1.1.1 --rm --net=none -v $PWD:/work -w /work quay.io/goswagger/swagger:v0.20.1 generate client -f ./client/swagger.yaml -T ./templates --model-package=client/models --client-package=client --copyright-file=COPYRIGHT_HEADER --skip-validation 21 | //go:generate docker run --add-host github.com:127.1.1.1 --rm --net=none -v $PWD:/work -w /work quay.io/goswagger/swagger:v0.20.1 generate client -f ./client/swagger.yaml -C ./go_swagger_layout.yaml -T ./templates --model-package=client/models --client-package=fctesting --copyright-file=COPYRIGHT_HEADER --skip-validation 22 | 23 | package firecracker 24 | -------------------------------------------------------------------------------- /templates/client/client.gotmpl: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | 4 | {{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }} 5 | 6 | 7 | package {{ .Name }} 8 | 9 | // This file was generated by the swagger tool. 10 | // Editing this file might prove futile when you re-run the swagger generate command 11 | 12 | import ( 13 | "net/http" 14 | "github.com/go-openapi/errors" 15 | "github.com/go-openapi/swag" 16 | "github.com/go-openapi/runtime" 17 | "github.com/go-openapi/validate" 18 | 19 | strfmt "github.com/go-openapi/strfmt" 20 | 21 | {{ range .DefaultImports }}{{ printf "%q" .}} 22 | {{ end }} 23 | {{ range $key, $value := .Imports }}{{ $key }} {{ printf "%q" $value }} 24 | {{ end }} 25 | ) 26 | 27 | // New creates a new {{ humanize .Name }} API client. 28 | func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { 29 | return &Client{transport: transport, formats: formats} 30 | } 31 | 32 | /* 33 | Client {{ if .Summary }}{{ .Summary }}{{ if .Description }} 34 | 35 | {{ blockcomment .Description }}{{ end }}{{ else if .Description}}{{ blockcomment .Description }}{{ else }}for {{ humanize .Name }} API{{ end }} 36 | */ 37 | type Client struct { 38 | transport runtime.ClientTransport 39 | formats strfmt.Registry 40 | } 41 | 42 | // NewClient will return a new client with the given transport and formats 43 | func NewClient(transport runtime.ClientTransport, formats strfmt.Registry) *Client { 44 | return &Client{ 45 | transport: transport, 46 | formats: formats, 47 | } 48 | } 49 | 50 | {{ range .Operations }}/* 51 | {{ pascalize .Name }} {{ if .Summary }}{{ pluralizeFirstWord (humanize .Summary) }}{{ if .Description }} 52 | 53 | {{ blockcomment .Description }}{{ end }}{{ else if .Description}}{{ blockcomment .Description }}{{ else }}{{ humanize .Name }} API{{ end }} 54 | */ 55 | func (a *Client) {{ pascalize .Name }}(params *{{ pascalize .Name }}Params{{ if .Authorized }}, authInfo runtime.ClientAuthInfoWriter{{end}}{{ if .HasStreamingResponse }}, writer io.Writer{{ end }}) {{ if .SuccessResponse }}({{ range .SuccessResponses }}*{{ pascalize .Name }}, {{ end }}{{ end }}error{{ if .SuccessResponse }}){{ end }} { 56 | // TODO: Validate the params before sending 57 | if params == nil { 58 | params = New{{ pascalize .Name }}Params() 59 | } 60 | {{ $length := len .SuccessResponses }} 61 | {{ if .SuccessResponse }}result{{else}}_{{ end }}, err := a.transport.Submit(&runtime.ClientOperation{ 62 | ID: {{ printf "%q" .Name }}, 63 | Method: {{ printf "%q" .Method }}, 64 | PathPattern: {{ printf "%q" .Path }}, 65 | ProducesMediaTypes: {{ printf "%#v" .ProducesMediaTypes }}, 66 | ConsumesMediaTypes: {{ printf "%#v" .ConsumesMediaTypes }}, 67 | Schemes: {{ printf "%#v" .Schemes }}, 68 | Params: params, 69 | Reader: &{{ pascalize .Name }}Reader{formats: a.formats{{ if .HasStreamingResponse }}, writer: writer{{ end }}},{{ if .Authorized }} 70 | AuthInfo: authInfo,{{ end}} 71 | Context: params.Context, 72 | Client: params.HTTPClient, 73 | }) 74 | if err != nil { 75 | return {{ if .SuccessResponse }}{{ padSurround "nil" "nil" 0 $length }}, {{ end }}err 76 | } 77 | {{ if .SuccessResponse }}{{ if eq $length 1 }}return result.(*{{ pascalize .SuccessResponse.Name }}), nil{{ else }}switch value := result.(type) { {{ range $i, $v := .SuccessResponses }} 78 | case *{{ pascalize $v.Name }}: 79 | return {{ padSurround "value" "nil" $i $length }}, nil{{ end }} } 80 | return {{ padSurround "nil" "nil" 0 $length }}, nil{{ end }} 81 | {{ else }}return nil{{ end }} 82 | 83 | } 84 | {{ end }} 85 | 86 | // SetTransport changes the transport on the client 87 | func (a *Client) SetTransport(transport runtime.ClientTransport) { 88 | a.transport = transport 89 | } 90 | 91 | // ClientIface is an interface that can be used to mock out a Firecracker agent 92 | // for testing purposes. 93 | type ClientIface interface { 94 | {{ range .Operations -}} 95 | {{ pascalize .Name }}(params *{{ pascalize .Name }}Params{{ if .Authorized }}, authInfo runtime.ClientAuthInfoWriter{{end}}{{ if .HasStreamingResponse }}, writer io.Writer{{ end }}) {{ if .SuccessResponse }}({{ range .SuccessResponses }}*{{ pascalize .Name }}, {{ end }}{{ end }}error{{ if .SuccessResponse }}){{ end }} 96 | {{ end -}} 97 | } 98 | -------------------------------------------------------------------------------- /templates/client/facade.gotmpl: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | 4 | {{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }} 5 | 6 | 7 | package {{ .Package }} 8 | 9 | // This file was generated by the swagger tool. 10 | // Editing this file might prove futile when you re-run the swagger generate command 11 | 12 | 13 | import ( 14 | "net/http" 15 | "github.com/go-openapi/runtime" 16 | httptransport "github.com/go-openapi/runtime/client" 17 | "github.com/go-openapi/swag" 18 | "github.com/go-openapi/spec" 19 | "github.com/go-openapi/errors" 20 | "github.com/go-openapi/runtime" 21 | 22 | strfmt "github.com/go-openapi/strfmt" 23 | 24 | {{ range .DefaultImports }}{{ printf "%q" .}} 25 | {{ end }} 26 | {{ range $key, $value := .Imports }}{{ $key }} {{ printf "%q" $value }} 27 | {{ end }} 28 | ) 29 | 30 | // Default {{ humanize .Name }} HTTP client. 31 | var Default = NewHTTPClient(nil) 32 | 33 | const ( 34 | // DefaultHost is the default Host 35 | // found in Meta (info) section of spec file 36 | DefaultHost string = {{ printf "%#v" .Host }} 37 | // DefaultBasePath is the default BasePath 38 | // found in Meta (info) section of spec file 39 | DefaultBasePath string = {{ printf "%#v" .BasePath }} 40 | ) 41 | 42 | // DefaultSchemes are the default schemes found in Meta (info) section of spec file 43 | var DefaultSchemes = {{ printf "%#v" .Schemes }} 44 | 45 | // NewHTTPClient creates a new {{ humanize .Name }} HTTP client. 46 | func NewHTTPClient(formats strfmt.Registry) *{{ pascalize .Name }} { 47 | return NewHTTPClientWithConfig(formats, nil) 48 | } 49 | 50 | // NewHTTPClientWithConfig creates a new {{ humanize .Name }} HTTP client, 51 | // using a customizable transport config. 52 | func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *{{ pascalize .Name }} { 53 | // ensure nullable parameters have default 54 | if cfg == nil { 55 | cfg = DefaultTransportConfig() 56 | } 57 | 58 | // create transport and client 59 | transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) 60 | return New(transport, formats) 61 | } 62 | 63 | // New creates a new {{ humanize .Name }} client 64 | func New(transport runtime.ClientTransport, formats strfmt.Registry) *{{ pascalize .Name }} { 65 | // ensure nullable parameters have default 66 | if formats == nil { 67 | formats = strfmt.Default 68 | } 69 | 70 | cli := new({{ pascalize .Name }}) 71 | cli.Transport = transport 72 | {{ range .OperationGroups }} 73 | cli.{{ pascalize .Name }} = {{ .Name }}.New(transport, formats) 74 | {{ end }} 75 | return cli 76 | } 77 | 78 | // DefaultTransportConfig creates a TransportConfig with the 79 | // default settings taken from the meta section of the spec file. 80 | func DefaultTransportConfig() *TransportConfig { 81 | return &TransportConfig { 82 | Host: DefaultHost, 83 | BasePath: DefaultBasePath, 84 | Schemes: DefaultSchemes, 85 | } 86 | } 87 | 88 | // TransportConfig contains the transport related info, 89 | // found in the meta section of the spec file. 90 | type TransportConfig struct { 91 | Host string 92 | BasePath string 93 | Schemes []string 94 | } 95 | 96 | // WithHost overrides the default host, 97 | // provided by the meta section of the spec file. 98 | func (cfg *TransportConfig) WithHost(host string) *TransportConfig { 99 | cfg.Host = host 100 | return cfg 101 | } 102 | 103 | // WithBasePath overrides the default basePath, 104 | // provided by the meta section of the spec file. 105 | func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { 106 | cfg.BasePath = basePath 107 | return cfg 108 | } 109 | 110 | // WithSchemes overrides the default schemes, 111 | // provided by the meta section of the spec file. 112 | func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { 113 | cfg.Schemes = schemes 114 | return cfg 115 | } 116 | 117 | // {{ pascalize .Name }} is a client for {{ humanize .Name }} 118 | type {{ pascalize .Name }} struct { 119 | {{ range .OperationGroups }} 120 | {{ pascalize .Name }} {{ .Name }}.ClientIface 121 | {{ end }} 122 | Transport runtime.ClientTransport 123 | } 124 | 125 | 126 | // SetTransport changes the transport on the client and all its subresources 127 | func (c *{{pascalize .Name}}) SetTransport(transport runtime.ClientTransport) { 128 | c.Transport = transport 129 | {{ range .OperationGroups }} 130 | c.{{ pascalize .Name }} = operations.NewClient(transport, nil) 131 | {{ end }} 132 | } 133 | -------------------------------------------------------------------------------- /templates/mockclient.gotmpl: -------------------------------------------------------------------------------- 1 | // Code generated by go-swagger; DO NOT EDIT. 2 | 3 | 4 | {{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }} 5 | 6 | 7 | package fctesting 8 | 9 | import ( 10 | ops "github.com/firecracker-microvm/firecracker-go-sdk/client/operations" 11 | ) 12 | 13 | type MockClient struct { 14 | {{ range .Operations -}} 15 | {{ pascalize .Name }}Fn func(params *ops.{{ pascalize .Name }}Params{{ if .Authorized }}, authInfo runtime.ClientAuthInfoWriter{{end}}{{ if .HasStreamingResponse }}, writer io.Writer{{ end }}) {{ if .SuccessResponse }}({{ range .SuccessResponses }}*ops.{{ pascalize .Name }}, {{ end }}{{ end }}error{{ if .SuccessResponse }}){{ end }} 16 | {{ end -}} 17 | } 18 | {{ range .Operations -}} 19 | 20 | func (c *MockClient) {{ pascalize .Name }}(params *ops.{{ pascalize .Name }}Params{{ if .Authorized }}, authInfo runtime.ClientAuthInfoWriter{{end}}{{ if .HasStreamingResponse }}, writer io.Writer{{ end }}) {{ if .SuccessResponse }}({{ range .SuccessResponses }}*ops.{{ pascalize .Name }}, {{ end }}{{ end }}error{{ if .SuccessResponse }}){{ end }} { 21 | if c.{{ pascalize .Name }}Fn != nil { 22 | return c.{{ pascalize .Name }}Fn(params{{ if .Authorized }}, authInfo{{end}}{{ if .HasStreamingResponse }}, writer{{ end }}) 23 | } 24 | 25 | return {{ if .SuccessResponse }}{{ range .SuccessResponses }}nil, {{ end }}{{ end }} nil 26 | } 27 | 28 | {{ end -}} 29 | -------------------------------------------------------------------------------- /testdata/drive-2.img: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/firecracker-microvm/firecracker-go-sdk/6f382b52ea2a3ce6ee007dae77d59c8642c73bdc/testdata/drive-2.img -------------------------------------------------------------------------------- /testdata/drive-3.img: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/firecracker-microvm/firecracker-go-sdk/6f382b52ea2a3ce6ee007dae77d59c8642c73bdc/testdata/drive-3.img -------------------------------------------------------------------------------- /testdata/sigprint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | typeset -i sig=1 4 | while (( sig < 65 )); do 5 | trap "echo '$sig'" $sig 2>/dev/null 6 | let sig=sig+1 7 | done 8 | 9 | >&2 echo "Send signals to PID $$ and type [q] when done." 10 | 11 | while : 12 | do 13 | read -n1 input 14 | [ "$input" == "q" ] && break 15 | sleep .1 16 | done 17 | -------------------------------------------------------------------------------- /utils.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package firecracker 14 | 15 | import ( 16 | "context" 17 | "os" 18 | "strconv" 19 | "time" 20 | ) 21 | 22 | const ( 23 | defaultAliveVMMCheckDur = 10 * time.Millisecond 24 | ) 25 | 26 | // waitForAliveVMM will check for periodically to see if the firecracker VMM is 27 | // alive. If the VMM takes too long in starting, an error signifying that will 28 | // be returned. 29 | func waitForAliveVMM(ctx context.Context, client *Client) error { 30 | t := time.NewTicker(defaultAliveVMMCheckDur) 31 | defer t.Stop() 32 | 33 | for { 34 | select { 35 | case <-ctx.Done(): 36 | return ctx.Err() 37 | case <-t.C: 38 | if _, err := client.GetMachineConfiguration(); err == nil { 39 | return nil 40 | } 41 | } 42 | } 43 | } 44 | 45 | // envValueOrDefaultInt check if env value exists and returns it or returns default value 46 | // provided as a second param to this function 47 | func envValueOrDefaultInt(envName string, def int) int { 48 | envVal, err := strconv.Atoi(os.Getenv(envName)) 49 | if envVal == 0 || err != nil { 50 | envVal = def 51 | } 52 | return envVal 53 | } 54 | -------------------------------------------------------------------------------- /utils_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | package firecracker 14 | 15 | import ( 16 | "testing" 17 | 18 | "github.com/stretchr/testify/assert" 19 | ) 20 | 21 | func TestEnvValueOrDefaultInt(t *testing.T) { 22 | defaultVal := 500 23 | assert.Equal(t, defaultVal, envValueOrDefaultInt("UNEXISTS_ENV", defaultVal)) 24 | } 25 | -------------------------------------------------------------------------------- /version.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package firecracker 15 | 16 | // Version represents the current version of the SDK. 17 | const Version = "1.0.0" 18 | -------------------------------------------------------------------------------- /vsock/dial_test.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package vsock 15 | 16 | import ( 17 | "errors" 18 | "testing" 19 | 20 | "github.com/stretchr/testify/assert" 21 | ) 22 | 23 | func TestTemporaryNetErr(t *testing.T) { 24 | assert.True(t, isTemporaryNetErr(&ackError{cause: errors.New("ack")})) 25 | 26 | assert.False(t, isTemporaryNetErr(&connectMsgError{cause: errors.New("connect")})) 27 | assert.False(t, isTemporaryNetErr(errors.New("something else"))) 28 | assert.False(t, isTemporaryNetErr(nil)) 29 | } 30 | -------------------------------------------------------------------------------- /vsock/listener.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may 4 | // not use this file except in compliance with the License. A copy of the 5 | // License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package vsock 15 | 16 | import ( 17 | "context" 18 | "fmt" 19 | "net" 20 | "time" 21 | 22 | "github.com/mdlayher/vsock" 23 | "github.com/sirupsen/logrus" 24 | ) 25 | 26 | type listener struct { 27 | listener net.Listener 28 | port uint32 29 | ctx context.Context 30 | config config 31 | } 32 | 33 | // Listener returns a net.Listener implementation for guest-side Firecracker 34 | // vsock connections. 35 | func Listener(ctx context.Context, logger *logrus.Entry, port uint32) (net.Listener, error) { 36 | l, err := vsock.Listen(port, nil) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | return listener{ 42 | listener: l, 43 | port: port, 44 | config: defaultConfig(), 45 | ctx: ctx, 46 | }, nil 47 | } 48 | 49 | func (l listener) Accept() (net.Conn, error) { 50 | ctx, cancel := context.WithTimeout(l.ctx, l.config.RetryTimeout) 51 | defer cancel() 52 | 53 | var attemptCount int 54 | ticker := time.NewTicker(l.config.RetryInterval) 55 | defer ticker.Stop() 56 | tickerCh := ticker.C 57 | for { 58 | attemptCount++ 59 | logger := l.config.logger.WithField("attempt", attemptCount) 60 | 61 | select { 62 | case <-ctx.Done(): 63 | return nil, ctx.Err() 64 | case <-tickerCh: 65 | conn, err := tryAccept(logger, l.listener, l.port) 66 | if isTemporaryNetErr(err) { 67 | err = fmt.Errorf("temporary vsock accept failure: %w", err) 68 | logger.WithError(err).Debug() 69 | continue 70 | } else if err != nil { 71 | err = fmt.Errorf("non-temporary vsock accept failure: %w", err) 72 | logger.WithError(err).Error() 73 | return nil, err 74 | } 75 | 76 | return conn, nil 77 | } 78 | } 79 | } 80 | 81 | func (l listener) Close() error { 82 | return l.listener.Close() 83 | } 84 | 85 | func (l listener) Addr() net.Addr { 86 | return l.listener.Addr() 87 | } 88 | 89 | // tryAccept attempts to accept a single host-side connection from the provided 90 | // guest-side listener at the provided port. 91 | func tryAccept(logger *logrus.Entry, listener net.Listener, port uint32) (net.Conn, error) { 92 | conn, err := listener.Accept() 93 | if err != nil { 94 | return nil, err 95 | } 96 | 97 | defer func() { 98 | if err != nil { 99 | closeErr := conn.Close() 100 | if closeErr != nil { 101 | logger.WithError(closeErr).Error( 102 | "failed to close vsock after previous error") 103 | } 104 | } 105 | }() 106 | 107 | return conn, nil 108 | } 109 | --------------------------------------------------------------------------------