Temporarily remove zfs as built in plugin

Signed-off-by: Derek McGowan <derek@mcg.dev>
This commit is contained in:
Derek McGowan 2023-10-10 15:51:31 -07:00
parent a7333657af
commit cb969085f5
No known key found for this signature in database
GPG Key ID: F58C5D0A4405ACDB
31 changed files with 8 additions and 2677 deletions

View File

@ -16,4 +16,6 @@
package builtins package builtins
import _ "github.com/containerd/zfs/plugin" // Temporarily removed while plugin package is moved, to be added back
// before 2.0.
//import _ "github.com/containerd/zfs/plugin"

View File

@ -18,4 +18,8 @@
package builtins package builtins
import _ "github.com/containerd/zfs/plugin" // zfs snapshotter is temporarily removed until it is updated to use the
// new plugin package. In the future, the external plugin package will
// make it easier to update zfs and containerd independently without
// the dependency loop. Add back before 2.0 release.
//import _ "github.com/containerd/zfs/plugin"

2
go.mod
View File

@ -21,7 +21,6 @@ require (
github.com/containerd/nri v0.5.0 github.com/containerd/nri v0.5.0
github.com/containerd/ttrpc v1.2.2 github.com/containerd/ttrpc v1.2.2
github.com/containerd/typeurl/v2 v2.1.1 github.com/containerd/typeurl/v2 v2.1.1
github.com/containerd/zfs v1.2.0
github.com/containernetworking/cni v1.1.2 github.com/containernetworking/cni v1.1.2
github.com/containernetworking/plugins v1.3.0 github.com/containernetworking/plugins v1.3.0
github.com/coreos/go-systemd/v22 v22.5.0 github.com/coreos/go-systemd/v22 v22.5.0
@ -103,7 +102,6 @@ require (
github.com/klauspost/cpuid/v2 v2.2.5 // indirect github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/miekg/pkcs11 v1.1.1 // indirect github.com/miekg/pkcs11 v1.1.1 // indirect
github.com/mistifyio/go-zfs/v3 v3.0.1 // indirect
github.com/moby/spdystream v0.2.0 // indirect github.com/moby/spdystream v0.2.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect

4
go.sum
View File

@ -295,8 +295,6 @@ github.com/containerd/zfs v0.0.0-20210301145711-11e8f1707f62/go.mod h1:A9zfAbMlQ
github.com/containerd/zfs v0.0.0-20210315114300-dde8f0fda960/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY= github.com/containerd/zfs v0.0.0-20210315114300-dde8f0fda960/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY=
github.com/containerd/zfs v0.0.0-20210324211415-d5c4544f0433/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY= github.com/containerd/zfs v0.0.0-20210324211415-d5c4544f0433/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY=
github.com/containerd/zfs v1.0.0/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY= github.com/containerd/zfs v1.0.0/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY=
github.com/containerd/zfs v1.2.0 h1:AtAkI6CIAtBV1Pu5/06r4fsHv9JQwZOt/NoKdhSi4qA=
github.com/containerd/zfs v1.2.0/go.mod h1:NinsnukMVY2SnwkJzrEhXzDDPdJ3Ok5LnGjblu1nfmI=
github.com/containernetworking/cni v0.7.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= github.com/containernetworking/cni v0.7.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY=
github.com/containernetworking/cni v0.8.0/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= github.com/containernetworking/cni v0.8.0/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY=
github.com/containernetworking/cni v0.8.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= github.com/containernetworking/cni v0.8.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY=
@ -693,8 +691,6 @@ github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WT
github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM=
github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8=
github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4= github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4=
github.com/mistifyio/go-zfs/v3 v3.0.1 h1:YaoXgBePoMA12+S1u/ddkv+QqxcfiZK4prI6HPnkFiU=
github.com/mistifyio/go-zfs/v3 v3.0.1/go.mod h1:CzVgeB0RvF2EGzQnytKVvVSDwmKJXxkOTUGbNrTja/k=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=

View File

@ -760,7 +760,6 @@ github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migc
github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=
github.com/Microsoft/hcsshim v0.8.15/go.mod h1:x38A4YbHbdxJtc0sF6oIz+RG0npwSCAvn69iY6URG00= github.com/Microsoft/hcsshim v0.8.15/go.mod h1:x38A4YbHbdxJtc0sF6oIz+RG0npwSCAvn69iY6URG00=
github.com/Microsoft/hcsshim v0.9.4/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc= github.com/Microsoft/hcsshim v0.9.4/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc=
github.com/Microsoft/hcsshim v0.9.6/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc=
github.com/Microsoft/hcsshim v0.9.9/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc= github.com/Microsoft/hcsshim v0.9.9/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc=
github.com/Microsoft/hcsshim v0.12.0-rc.0 h1:wX/F5huJxH9APBkhKSEAqaiZsuBvbbDnyBROZAqsSaY= github.com/Microsoft/hcsshim v0.12.0-rc.0 h1:wX/F5huJxH9APBkhKSEAqaiZsuBvbbDnyBROZAqsSaY=
github.com/Microsoft/hcsshim v0.12.0-rc.0/go.mod h1:rvOnw3YlfoNnEp45wReUngvsXbwRW+AFQ10GVjG1kMU= github.com/Microsoft/hcsshim v0.12.0-rc.0/go.mod h1:rvOnw3YlfoNnEp45wReUngvsXbwRW+AFQ10GVjG1kMU=
@ -873,7 +872,6 @@ github.com/container-orchestrated-devices/container-device-interface v0.6.1/go.m
github.com/containerd/btrfs/v2 v2.0.0/go.mod h1:swkD/7j9HApWpzl8OHfrHNxppPd9l44DFZdF94BUj9k= github.com/containerd/btrfs/v2 v2.0.0/go.mod h1:swkD/7j9HApWpzl8OHfrHNxppPd9l44DFZdF94BUj9k=
github.com/containerd/cgroups v0.0.0-20200824123100-0b889c03f102/go.mod h1:s5q4SojHctfxANBDvMeIaIovkq29IP48TKAxnhYRxvo= github.com/containerd/cgroups v0.0.0-20200824123100-0b889c03f102/go.mod h1:s5q4SojHctfxANBDvMeIaIovkq29IP48TKAxnhYRxvo=
github.com/containerd/cgroups v1.0.1/go.mod h1:0SJrPIenamHDcZhEcJMNBB85rHcUsw4f25ZfBiPYRkU= github.com/containerd/cgroups v1.0.1/go.mod h1:0SJrPIenamHDcZhEcJMNBB85rHcUsw4f25ZfBiPYRkU=
github.com/containerd/cgroups v1.0.4/go.mod h1:nLNQtsF7Sl2HxNebu77i1R0oDlhiTG+kO4JTrUzo6IA=
github.com/containerd/cgroups v1.1.0/go.mod h1:6ppBcbh/NOOUU+dMKrykgaBnK9lCIBxHqJDGwsa1mIw= github.com/containerd/cgroups v1.1.0/go.mod h1:6ppBcbh/NOOUU+dMKrykgaBnK9lCIBxHqJDGwsa1mIw=
github.com/containerd/cgroups/v3 v3.0.2 h1:f5WFqIVSgo5IZmtTT3qVBo6TzI1ON6sycSBKkymb9L0= github.com/containerd/cgroups/v3 v3.0.2 h1:f5WFqIVSgo5IZmtTT3qVBo6TzI1ON6sycSBKkymb9L0=
github.com/containerd/cgroups/v3 v3.0.2/go.mod h1:JUgITrzdFqp42uI2ryGA+ge0ap/nxzYgkGmIcetmErE= github.com/containerd/cgroups/v3 v3.0.2/go.mod h1:JUgITrzdFqp42uI2ryGA+ge0ap/nxzYgkGmIcetmErE=
@ -882,7 +880,6 @@ github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4q
github.com/containerd/console v1.0.2/go.mod h1:ytZPjGgY2oeTkAONYafi2kSj0aYggsf8acV1PGKCbzQ= github.com/containerd/console v1.0.2/go.mod h1:ytZPjGgY2oeTkAONYafi2kSj0aYggsf8acV1PGKCbzQ=
github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARubLw= github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARubLw=
github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=
github.com/containerd/continuity v0.3.0/go.mod h1:wJEAIwKOm/pBZuBd0JmeTvnLquTB1Ag8espWhkykbPM=
github.com/containerd/continuity v0.4.1/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ= github.com/containerd/continuity v0.4.1/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ=
github.com/containerd/continuity v0.4.2 h1:v3y/4Yz5jwnvqPKJJ+7Wf93fyWoCB3F5EclWG023MDM= github.com/containerd/continuity v0.4.2 h1:v3y/4Yz5jwnvqPKJJ+7Wf93fyWoCB3F5EclWG023MDM=
github.com/containerd/continuity v0.4.2/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ= github.com/containerd/continuity v0.4.2/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ=
@ -911,7 +908,6 @@ github.com/containerd/typeurl v1.0.1/go.mod h1:TB1hUtrpaiO88KEK56ijojHS1+NeF0izU
github.com/containerd/typeurl v1.0.2/go.mod h1:9trJWW2sRlGub4wZJRTW83VtbOLS6hwcDZXTn6oPz9s= github.com/containerd/typeurl v1.0.2/go.mod h1:9trJWW2sRlGub4wZJRTW83VtbOLS6hwcDZXTn6oPz9s=
github.com/containerd/typeurl/v2 v2.1.1 h1:3Q4Pt7i8nYwy2KmQWIw2+1hTvwTE/6w9FqcttATPO/4= github.com/containerd/typeurl/v2 v2.1.1 h1:3Q4Pt7i8nYwy2KmQWIw2+1hTvwTE/6w9FqcttATPO/4=
github.com/containerd/typeurl/v2 v2.1.1/go.mod h1:IDp2JFvbwZ31H8dQbEIY7sDl2L3o3HZj1hsSQlywkQ0= github.com/containerd/typeurl/v2 v2.1.1/go.mod h1:IDp2JFvbwZ31H8dQbEIY7sDl2L3o3HZj1hsSQlywkQ0=
github.com/containerd/zfs v1.2.0/go.mod h1:NinsnukMVY2SnwkJzrEhXzDDPdJ3Ok5LnGjblu1nfmI=
github.com/containernetworking/cni v1.1.1/go.mod h1:sDpYKmGVENF3s6uvMvGgldDWeG8dMxakj/u+i9ht9vw= github.com/containernetworking/cni v1.1.1/go.mod h1:sDpYKmGVENF3s6uvMvGgldDWeG8dMxakj/u+i9ht9vw=
github.com/containernetworking/cni v1.1.2/go.mod h1:sDpYKmGVENF3s6uvMvGgldDWeG8dMxakj/u+i9ht9vw= github.com/containernetworking/cni v1.1.2/go.mod h1:sDpYKmGVENF3s6uvMvGgldDWeG8dMxakj/u+i9ht9vw=
github.com/containernetworking/plugins v1.3.0/go.mod h1:Pc2wcedTQQCVuROOOaLBPPxrEXqqXBFt3cZ+/yVg6l0= github.com/containernetworking/plugins v1.3.0/go.mod h1:Pc2wcedTQQCVuROOOaLBPPxrEXqqXBFt3cZ+/yVg6l0=
@ -1195,7 +1191,6 @@ github.com/google/s2a-go v0.1.0/go.mod h1:OJpEgntRZo8ugHpF9hkoLJbS5dSI20XZeXJ9JV
github.com/google/s2a-go v0.1.3/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/s2a-go v0.1.3/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A=
github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@ -1366,7 +1361,6 @@ github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WT
github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY= github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY=
github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE= github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE=
github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8=
github.com/mistifyio/go-zfs/v3 v3.0.1/go.mod h1:CzVgeB0RvF2EGzQnytKVvVSDwmKJXxkOTUGbNrTja/k=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
@ -1454,7 +1448,6 @@ github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3I
github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
github.com/opencontainers/image-spec v1.0.3-0.20211202183452-c5a74bcca799/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= github.com/opencontainers/image-spec v1.0.3-0.20211202183452-c5a74bcca799/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
github.com/opencontainers/image-spec v1.1.0-rc2/go.mod h1:3OVijpioIKYWTqjiG0zfF6wvoJ4fAXGbjdZuI2NgsRQ=
github.com/opencontainers/image-spec v1.1.0-rc3/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8= github.com/opencontainers/image-spec v1.1.0-rc3/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8=
github.com/opencontainers/image-spec v1.1.0-rc4 h1:oOxKUJWnFC4YGHCCMNql1x4YaDfYBTS5Y4x/Cgeo1E0= github.com/opencontainers/image-spec v1.1.0-rc4 h1:oOxKUJWnFC4YGHCCMNql1x4YaDfYBTS5Y4x/Cgeo1E0=
github.com/opencontainers/image-spec v1.1.0-rc4/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8= github.com/opencontainers/image-spec v1.1.0-rc4/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8=
@ -2068,7 +2061,6 @@ golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220405210540-1e041c57c461/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@ -2572,7 +2564,6 @@ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk=
gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8=
gotest.tools/v3 v3.4.0/go.mod h1:CtbdzLSsqVhDgMtKsx03ird5YTGB3ar27v0u/yKBW5g=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@ -1,4 +0,0 @@
*.test
# Support running go modules in vendor mode for local development
/vendor/

View File

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,35 +0,0 @@
# [containerd](https://github.com/containerd/containerd) ZFS snapshotter plugin
[![PkgGoDev](https://pkg.go.dev/badge/github.com/containerd/zfs)](https://pkg.go.dev/github.com/containerd/zfs)
[![Build Status](https://github.com/containerd/zfs/actions/workflows/ci.yml/badge.svg)](https://github.com/containerd/zfs/actions/workflows/ci.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/containerd/zfs)](https://goreportcard.com/report/github.com/containerd/zfs)
[![codecov](https://codecov.io/gh/containerd/zfs/branch/main/graph/badge.svg)](https://codecov.io/gh/containerd/zfs)
ZFS snapshotter plugin for containerd.
This plugin is tested on Linux with Ubuntu. It should be compatible with FreeBSD.
## Usage
The plugin is built-in by default since containerd 1.1.
No need to recompile containerd or execute a proxy snapshotter process.
1. Set up a ZFS filesystem.
The ZFS filesystem name is arbitrary but the mount point needs to be `/var/lib/containerd/io.containerd.snapshotter.v1.zfs`, when the containerd root is set to `/var/lib/containerd`.
```console
$ zfs create -o mountpoint=/var/lib/containerd/io.containerd.snapshotter.v1.zfs your-zpool/containerd
```
2. Start containerd.
3. e.g. `ctr pull --snapshotter=zfs ...`
## Project details
The zfs plugin is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE).
As a containerd sub-project, you will find the:
* [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md),
* [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS),
* and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md)
information in our [`containerd/project`](https://github.com/containerd/project) repository.

View File

@ -1 +0,0 @@
comment: false

View File

@ -1,62 +0,0 @@
//go:build linux || freebsd
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package plugin
import (
"errors"
"fmt"
"github.com/containerd/containerd/platforms"
"github.com/containerd/containerd/plugin"
"github.com/containerd/zfs"
)
// Config represents configuration for the zfs plugin
type Config struct {
// Root directory for the plugin
RootPath string `toml:"root_path"`
}
func init() {
plugin.Register(&plugin.Registration{
Type: plugin.SnapshotPlugin,
ID: "zfs",
Config: &Config{},
InitFn: func(ic *plugin.InitContext) (interface{}, error) {
ic.Meta.Platforms = append(ic.Meta.Platforms, platforms.DefaultSpec())
// get config
config, ok := ic.Config.(*Config)
if !ok {
return nil, errors.New("invalid zfs configuration")
}
// use default ic.Root as root path if config doesn't have a valid root path
root := ic.Root
if len(config.RootPath) != 0 {
root = config.RootPath
}
ic.Meta.Exports["root"] = root
snapshotter, err := zfs.NewSnapshotter(root)
if err != nil {
return nil, fmt.Errorf("%s: %w", err.Error(), plugin.ErrSkipPlugin)
}
return snapshotter, nil
},
})
}

View File

@ -1,368 +0,0 @@
//go:build linux || freebsd
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package zfs
import (
"context"
"fmt"
"math"
"path/filepath"
"github.com/containerd/containerd/mount"
"github.com/containerd/containerd/snapshots"
"github.com/containerd/containerd/snapshots/storage"
"github.com/containerd/log"
"github.com/mistifyio/go-zfs/v3"
)
const (
// snapshotSuffix is used as follows:
// active := filepath.Join(dataset.Name, id)
// committed := active + "@" + snapshotSuffix
snapshotSuffix = "snapshot"
// Using this typed MaxInt64 to prevent integer overlow on 32bit
maxSnapshotSize int64 = math.MaxInt64
)
type snapshotter struct {
dataset *zfs.Dataset
ms *storage.MetaStore
}
// NewSnapshotter returns a Snapshotter using zfs. Uses the provided
// root directory for snapshots and stores the metadata in
// a file in the provided root.
// root needs to be a mount point of zfs.
func NewSnapshotter(root string) (snapshots.Snapshotter, error) {
m, err := mount.Lookup(root)
if err != nil {
return nil, err
}
if m.FSType != "zfs" {
return nil, fmt.Errorf("path %s must be a zfs filesystem to be used with the zfs snapshotter", root)
}
dataset, err := zfs.GetDataset(m.Source)
if err != nil {
return nil, err
}
ms, err := storage.NewMetaStore(filepath.Join(root, "metadata.db"))
if err != nil {
return nil, err
}
b := &snapshotter{
dataset: dataset,
ms: ms,
}
return b, nil
}
var zfsCreateProperties = map[string]string{
"mountpoint": "legacy",
}
// createFilesystem creates but not mount.
func createFilesystem(datasetName string) (*zfs.Dataset, error) {
return zfs.CreateFilesystem(datasetName, zfsCreateProperties)
}
// cloneFilesystem clones but not mount.
func cloneFilesystem(datasetName string, snapshot *zfs.Dataset) (*zfs.Dataset, error) {
return snapshot.Clone(datasetName, zfsCreateProperties)
}
func destroy(dataset *zfs.Dataset) error {
return dataset.Destroy(zfs.DestroyDefault)
}
func destroySnapshot(dataset *zfs.Dataset) error {
return dataset.Destroy(zfs.DestroyDeferDeletion)
}
// Stat returns the info for an active or committed snapshot by name or
// key.
//
// Should be used for parent resolution, existence checks and to discern
// the kind of snapshot.
func (z *snapshotter) Stat(ctx context.Context, key string) (snapshots.Info, error) {
ctx, t, err := z.ms.TransactionContext(ctx, false)
if err != nil {
return snapshots.Info{}, err
}
defer t.Rollback() //nolint:errcheck
_, info, _, err := storage.GetInfo(ctx, key)
if err != nil {
return snapshots.Info{}, err
}
return info, nil
}
// Usage retrieves the disk usage of the top-level snapshot.
func (z *snapshotter) Usage(ctx context.Context, key string) (snapshots.Usage, error) {
return z.usage(ctx, key)
}
func (z *snapshotter) usage(ctx context.Context, key string) (snapshots.Usage, error) {
ctx, t, err := z.ms.TransactionContext(ctx, false)
if err != nil {
return snapshots.Usage{}, err
}
id, info, usage, err := storage.GetInfo(ctx, key)
t.Rollback() //nolint:errcheck
if err != nil {
return snapshots.Usage{}, err
}
if info.Kind == snapshots.KindActive {
activeName := filepath.Join(z.dataset.Name, id)
sDataset, err := zfs.GetDataset(activeName)
if err != nil {
return snapshots.Usage{}, err
}
if int64(sDataset.Used) > maxSnapshotSize {
return snapshots.Usage{}, fmt.Errorf("Dataset size exceeds maximum snapshot size of %d bytes", maxSnapshotSize)
}
usage = snapshots.Usage{
Size: int64(sDataset.Used),
Inodes: -1,
}
}
return usage, nil
}
// Walk the committed snapshots.
func (z *snapshotter) Walk(ctx context.Context, fn snapshots.WalkFunc, filters ...string) error {
ctx, t, err := z.ms.TransactionContext(ctx, false)
if err != nil {
return err
}
defer t.Rollback() //nolint:errcheck
return storage.WalkInfo(ctx, fn, filters...)
}
func (z *snapshotter) Prepare(ctx context.Context, key, parent string, opts ...snapshots.Opt) ([]mount.Mount, error) {
return z.createSnapshot(ctx, snapshots.KindActive, key, parent, opts...)
}
func (z *snapshotter) View(ctx context.Context, key, parent string, opts ...snapshots.Opt) ([]mount.Mount, error) {
return z.createSnapshot(ctx, snapshots.KindView, key, parent, opts...)
}
func (z *snapshotter) createSnapshot(ctx context.Context, kind snapshots.Kind, key, parent string, opts ...snapshots.Opt) ([]mount.Mount, error) {
ctx, t, err := z.ms.TransactionContext(ctx, true)
if err != nil {
return nil, err
}
defer func() {
if err != nil && t != nil {
if rerr := t.Rollback(); rerr != nil {
log.G(ctx).WithError(rerr).Warn("Failure rolling back transaction")
}
}
}()
a, err := storage.CreateSnapshot(ctx, kind, key, parent, opts...)
if err != nil {
return nil, err
}
targetName := filepath.Join(z.dataset.Name, a.ID)
var target *zfs.Dataset
if len(a.ParentIDs) == 0 {
target, err = createFilesystem(targetName)
if err != nil {
return nil, err
}
} else {
parent0Name := filepath.Join(z.dataset.Name, a.ParentIDs[0]) + "@" + snapshotSuffix
parent0, err := zfs.GetDataset(parent0Name)
if err != nil {
return nil, err
}
target, err = cloneFilesystem(targetName, parent0)
if err != nil {
return nil, err
}
}
err = t.Commit()
t = nil
if err != nil {
if derr := destroy(target); derr != nil {
log.G(ctx).WithError(derr).WithField("targetName", targetName).Error("failed to delete dataset")
}
return nil, err
}
readonly := kind == snapshots.KindView
return z.mounts(target, readonly)
}
func (z *snapshotter) mounts(dataset *zfs.Dataset, readonly bool) ([]mount.Mount, error) {
var options []string
if readonly {
options = append(options, "ro")
}
return []mount.Mount{
{
Type: "zfs",
Source: dataset.Name,
Options: options,
},
}, nil
}
func (z *snapshotter) Commit(ctx context.Context, name, key string, opts ...snapshots.Opt) (err error) {
usage, err := z.usage(ctx, key)
if err != nil {
return fmt.Errorf("failed to compute usage: %w", err)
}
ctx, t, err := z.ms.TransactionContext(ctx, true)
if err != nil {
return err
}
defer func() {
if err != nil && t != nil {
if rerr := t.Rollback(); rerr != nil {
log.G(ctx).WithError(rerr).Warn("Failure rolling back transaction")
}
}
}()
id, err := storage.CommitActive(ctx, key, name, usage, opts...)
if err != nil {
return fmt.Errorf("failed to commit: %w", err)
}
activeName := filepath.Join(z.dataset.Name, id)
active, err := zfs.GetDataset(activeName)
if err != nil {
return err
}
snapshot, err := active.Snapshot(snapshotSuffix, false)
if err != nil {
return err
}
err = t.Commit()
t = nil
if err != nil {
snapshotName := activeName + "@" + snapshotSuffix
if derr := destroySnapshot(snapshot); derr != nil {
log.G(ctx).WithError(derr).WithField("snapshotName", snapshotName).Error("failed to delete dataset")
}
return err
}
return nil
}
// Mounts returns the mounts for the transaction identified by key. Can be
// called on an read-write or readonly transaction.
//
// This can be used to recover mounts after calling View or Prepare.
func (z *snapshotter) Mounts(ctx context.Context, key string) ([]mount.Mount, error) {
ctx, t, err := z.ms.TransactionContext(ctx, false)
if err != nil {
return nil, err
}
s, err := storage.GetSnapshot(ctx, key)
t.Rollback() //nolint:errcheck
if err != nil {
return nil, fmt.Errorf("failed to get active snapshot: %w", err)
}
sName := filepath.Join(z.dataset.Name, s.ID)
sDataset, err := zfs.GetDataset(sName)
if err != nil {
return nil, err
}
return z.mounts(sDataset, false)
}
// Remove abandons the transaction identified by key. All resources
// associated with the key will be removed.
func (z *snapshotter) Remove(ctx context.Context, key string) (err error) {
ctx, t, err := z.ms.TransactionContext(ctx, true)
if err != nil {
return err
}
defer func() {
if err != nil && t != nil {
if rerr := t.Rollback(); rerr != nil {
log.G(ctx).WithError(rerr).Warn("Failure rolling back transaction")
}
}
// FIXME: rolling back the removed ZFS dataset is unsupported yet
}()
id, k, err := storage.Remove(ctx, key)
if err != nil {
return fmt.Errorf("failed to remove snapshot: %w", err)
}
datasetName := filepath.Join(z.dataset.Name, id)
if k == snapshots.KindCommitted {
snapshotName := datasetName + "@" + snapshotSuffix
snapshot, err := zfs.GetDataset(snapshotName)
if err != nil {
return err
}
if err = destroySnapshot(snapshot); err != nil {
return err
}
}
dataset, err := zfs.GetDataset(datasetName)
if err != nil {
return err
}
if err = destroy(dataset); err != nil {
return err
}
err = t.Commit()
t = nil
return err
}
func (o *snapshotter) Update(ctx context.Context, info snapshots.Info, fieldpaths ...string) (snapshots.Info, error) {
ctx, t, err := o.ms.TransactionContext(ctx, true)
if err != nil {
return snapshots.Info{}, err
}
info, err = storage.UpdateInfo(ctx, info, fieldpaths...)
if err != nil {
t.Rollback() //nolint:errcheck
return snapshots.Info{}, err
}
if err := t.Commit(); err != nil {
return snapshots.Info{}, err
}
return info, nil
}
func (o *snapshotter) Close() error {
return o.ms.Close()
}

View File

@ -1,4 +0,0 @@
has nix && use nix
dotenv_if_exists
PATH_add bin
path_add GOBIN bin

View File

@ -1,6 +0,0 @@
bin
go-zfs.test
.vagrant
# added by lint-install
out/

View File

@ -1,207 +0,0 @@
run:
# The default runtime timeout is 1m, which doesn't work well on Github Actions.
timeout: 4m
# NOTE: This file is populated by the lint-install tool. Local adjustments may be overwritten.
linters-settings:
cyclop:
# NOTE: This is a very high transitional threshold
max-complexity: 37
package-average: 34.0
skip-tests: true
gocognit:
# NOTE: This is a very high transitional threshold
min-complexity: 98
dupl:
threshold: 200
goconst:
min-len: 4
min-occurrences: 5
ignore-tests: true
gosec:
excludes:
- G107 # Potential HTTP request made with variable url
- G204 # Subprocess launched with function call as argument or cmd arguments
- G404 # Use of weak random number generator (math/rand instead of crypto/rand
errorlint:
# these are still common in Go: for instance, exit errors.
asserts: false
exhaustive:
default-signifies-exhaustive: true
nestif:
min-complexity: 8
nolintlint:
require-explanation: true
allow-unused: false
require-specific: true
revive:
ignore-generated-header: true
severity: warning
rules:
- name: atomic
- name: blank-imports
- name: bool-literal-in-expr
- name: confusing-naming
- name: constant-logical-expr
- name: context-as-argument
- name: context-keys-type
- name: deep-exit
- name: defer
- name: range-val-in-closure
- name: range-val-address
- name: dot-imports
- name: error-naming
- name: error-return
- name: error-strings
- name: errorf
- name: exported
- name: identical-branches
- name: if-return
- name: import-shadowing
- name: increment-decrement
- name: indent-error-flow
- name: indent-error-flow
- name: package-comments
- name: range
- name: receiver-naming
- name: redefines-builtin-id
- name: superfluous-else
- name: struct-tag
- name: time-naming
- name: unexported-naming
- name: unexported-return
- name: unnecessary-stmt
- name: unreachable-code
- name: unused-parameter
- name: var-declaration
- name: var-naming
- name: unconditional-recursion
- name: waitgroup-by-value
staticcheck:
go: "1.16"
unused:
go: "1.16"
output:
sort-results: true
linters:
disable-all: true
enable:
- asciicheck
- bodyclose
- cyclop
- deadcode
- dogsled
- dupl
- durationcheck
- errcheck
- errname
- errorlint
- exhaustive
- exportloopref
- forcetypeassert
- gocognit
- goconst
- gocritic
- godot
- gofmt
- gofumpt
- gosec
- goheader
- goimports
- goprintffuncname
- gosimple
- govet
- ifshort
- importas
- ineffassign
- makezero
- misspell
- nakedret
- nestif
- nilerr
- noctx
- nolintlint
- predeclared
# disabling for the initial iteration of the linting tool
# - promlinter
- revive
- rowserrcheck
- sqlclosecheck
- staticcheck
- structcheck
- stylecheck
- thelper
- tparallel
- typecheck
- unconvert
- unparam
- unused
- varcheck
- wastedassign
- whitespace
# Disabled linters, due to being misaligned with Go practices
# - exhaustivestruct
# - gochecknoglobals
# - gochecknoinits
# - goconst
# - godox
# - goerr113
# - gomnd
# - lll
# - nlreturn
# - testpackage
# - wsl
# Disabled linters, due to not being relevant to our code base:
# - maligned
# - prealloc "For most programs usage of prealloc will be a premature optimization."
# Disabled linters due to bad error messages or bugs
# - tagliatelle
issues:
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
- path: _test\.go
linters:
- dupl
- errcheck
- forcetypeassert
- gocyclo
- gosec
- noctx
- path: .*cmd.*
linters:
- noctx
- path: main\.go
linters:
- noctx
- path: .*cmd.*
text: "deep-exit"
- path: main\.go
text: "deep-exit"
# This check is of questionable value
- linters:
- tparallel
text: "call t.Parallel on the top level as well as its subtests"
# Don't hide lint issues just because there are many of them
max-same-issues: 0
max-issues-per-linter: 0

View File

@ -1,16 +0,0 @@
---
extends: default
rules:
braces:
max-spaces-inside: 1
brackets:
max-spaces-inside: 1
comments: disable
comments-indentation: disable
document-start: disable
line-length:
level: warning
max: 160
allow-non-breakable-inline-mappings: true
truthy: disable

View File

@ -1,250 +0,0 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
This change log follows the advice of [Keep a CHANGELOG](https://github.com/olivierlacan/keep-a-changelog).
## [Unreleased]
## [3.0.0] - 2022-03-30
### Added
- Rename, Mount and Unmount methods
- Parse more fields into Zpool type:
- dedupratio
- fragmentation
- freeing
- leaked
- readonly
- Parse more fields into Dataset type:
- referenced
- Incremental Send
- Parse numbers in exact format
- Support for Solaris (non-blockint, best-effort status)
- Debug logging for command invocation
- Use GitHub Actions for CI
- Nix shell for dev env reproducibility
- Direnv file for ease of dev
- Formatting/lint checks (enforced by CI)
- Go Module
- FreeBSD based vagrant machine
### Changed
- Temporarily adjust TestDiff expected strings depending on ZFS version
- Use one `zfs list`/`zpool list` call instead of many `zfs get`/`zpool get`
- ZFS docs links now point to OpenZFS pages
- Ubuntu vagrant box changed to generic/ubuntu2004
### Fixed
- `GetProperty` returning `VALUE` instead of the actual value
### Shortlog
Amit Krishnan (1):
Issue #39 and Issue #40 - Enable Solaris support for go-zfs Switch from zfs/zpool get to zfs/zpool list for better performance Signed-off-by: Amit Krishnan <krish.amit@gmail.com>
Anand Patil (3):
Added Rename
Small fix to rename.
Added mount and umount methods
Brian Akins (1):
Add 'referenced' to zfs properties
Brian Bickerton (3):
Add debug logging before and after running external zfs command
Don't export the default no-op logger
Update uuid package repo url
Dmitry Teselkin (1):
Issue #52 - fix parseLine for fragmentation field
Edward Betts (1):
correct spelling mistake
Justin Cormack (1):
Switch to google/uuid which is the maintained version of pborman/uuid
Manuel Mendez (40):
rename Umount -> Unmount to follow zfs command name
add missing Unmount/Mount docs
always allocate largest Mount slice
add travis config
travis: update to go 1.7
travis: get go deps first
test: add nok helper to verify an error occurred
test: add test for Dataset.GetProperty
ci: swap #cerana on freenode for slack
ci: install new deps for 0.7 relases
ci: bump zol versions
ci: bump go versions
ci: use better gometalinter invocations
ci: add ccache
ci: set env earlier in before_install
fix test nok error printing
test: restructure TestDiff to deal with different order of changes
test: better unicode path handling in TestDiff
travis: bump zfs and go versions
cache zfs artifacts
Add nix-shell and direnv goodness
prettierify all the files
Add go based tools
Add Makefile and rules.mk files
gofumptize the code base
Use tinkerbell/lint-install to setup linters
make golangci-lint happy
Update CONTRIBUTING.md with make based approach
Add GitHub Actions
Drop Travis CI
One sentence per line
Update documentation links to openzfs-docs pages
Format Vagrantfile using rufo
Add go-zfs.test to .gitignore
test: Avoid reptitive/duplicate error logging and quitting
test: Use t.Logf instead of fmt.Printf
test: Better cleanup and error handling in zpoolTest
test: Do not mark TestDatasets as a t.Helper.
test: Change zpoolTest to a pure helper that returns a clean up function
test: Move helpers to a different file
vagrant: Add set -euxo pipefail to provision script
vagrant: Update to generic/ubuntu2004
vagrant: Minor fixes to Vagrantfile
vagrant: Update to go 1.17.8
vagrant: Run go tests as part of provision script
vagrant: Indent heredoc script
vagrant: Add freebsd machine
Matt Layher (1):
Parse more fields into Zpool type
Michael Crosby (1):
Add incremental send
Rikard Gynnerstedt (1):
remove command name from joined args
Sebastiaan van Stijn (1):
Add go.mod and rename to github.com/mistifyio/go-zfs/v3 (v3.0.0)
mikudeko (1):
Fix GetProperty always returning 'VALUE'
## [2.1.1] - 2015-05-29
### Fixed
- Ignoring first pool listed
- Incorrect `zfs get` argument ordering
### Shortlog
Alexey Guskov (1):
zfs command uses different order of arguments on freebsd
Brian Akins (4):
test that ListZpools returns expected zpool
test error first
test error first
fix test to check correct return value
James Cunningham (1):
Fix Truncating First Zpool
Pat Norton (2):
Added Use of Go Tools
Update CONTRIBUTING.md
## [2.1.0] - 2014-12-08
### Added
- Parse hardlink modification count returned from `zfs diff`
### Fixed
- Continuing instead of erroring when rolling back a non-snapshot
### Shortlog
Brian Akins (2):
need to return the error here
use named struct fields
Jörg Thalheim (1):
zfs diff handle hardlinks modification now
## [2.0.0] - 2014-12-02
### Added
- Flags for Destroy:
- DESTROY_DEFAULT
- DESTROY_DEFER_DELETION (`zfs destroy ... -d`)
- DESTROY_FORCE (`zfs destroy ... -f`)
- DESTROY_RECURSIVE_CLONES (`zfs destroy ... -R`)
- DESTROY_RECURSIVE (`zfs destroy ... -r`)
- etc
- Diff method (`zfs diff`)
- LogicalUsed and Origin properties to Dataset
- Type constants for Dataset
- State constants for Zpool
- Logger interface
- Improve documentation
### Shortlog
Brian Akins (8):
remove reflection
style change for switches
need to check for error
keep in scope
go 1.3.3
golint cleanup
Just test if logical used is greater than 0, as this appears to be implementation specific
add docs to satisfy golint
Jörg Thalheim (8):
Add deferred flag to zfs.Destroy()
add Logicalused property
Add Origin property
gofmt
Add zfs.Diff
Add Logger
add recursive destroy with clones
use CamelCase-style constants
Matt Layher (4):
Improve documentation, document common ZFS operations, provide more references
Add zpool state constants, for easier health checking
Add dataset type constants, for easier type checking
Fix string split in command.Run(), use strings.Fields() instead of strings.Split()
## [1.0.0] - 2014-11-12
### Shortlog
Brian Akins (7):
add godoc badge
Add example
add information about zpool to struct and parser
Add Quota
add Children call
add Children call
fix snapshot tests
Brian Bickerton (3):
MIST-150 Change Snapshot second paramater from properties map[string][string] to recursive bool
MIST-150 Add Rollback method and related tests
MIST-160 Add SendSnapshot streaming method and tests
Matt Layher (1):
Add Error struct type and tests, enabling easier error return checking
[3.0.0]: https://github.com/mistifyio/go-zfs/compare/v2.1.1...v3.0.0
[2.1.1]: https://github.com/mistifyio/go-zfs/compare/v2.1.0...v2.1.1
[2.1.0]: https://github.com/mistifyio/go-zfs/compare/v2.0.0...v2.1.0
[2.0.0]: https://github.com/mistifyio/go-zfs/compare/v1.0.0...v2.0.0
[1.0.0]: https://github.com/mistifyio/go-zfs/compare/v0.0.0...v1.0.0

View File

@ -1,64 +0,0 @@
## How to Contribute
We always welcome contributions to help make `go-zfs` better.
Please take a moment to read this document if you would like to contribute.
### Reporting issues
We use [Github issues](https://github.com/mistifyio/go-zfs/issues) to track bug reports, feature requests, and submitting pull requests.
If you find a bug:
- Use the GitHub issue search to check whether the bug has already been reported.
- If the issue has been fixed, try to reproduce the issue using the latest `master` branch of the repository.
- If the issue still reproduces or has not yet been reported, try to isolate the problem before opening an issue, if possible. Also provide the steps taken to reproduce the bug.
### Pull requests
We welcome bug fixes, improvements, and new features.
Before embarking on making significant changes, please open an issue and ask first so that you do not risk duplicating efforts or spending time working on something that may be out of scope.
For minor items, just open a pull request.
[Fork the project](https://help.github.com/articles/fork-a-repo), clone your fork, and add the upstream to your remote:
$ git clone git@github.com:<your-username>/go-zfs.git
$ cd go-zfs
$ git remote add upstream https://github.com/mistifyio/go-zfs.git
If you need to pull new changes committed upstream:
$ git checkout master
$ git fetch upstream
$ git merge upstream/master
Don' work directly on master as this makes it harder to merge later.
Create a feature branch for your fix or new feature:
$ git checkout -b <feature-branch-name>
Please try to commit your changes in logical chunks.
Ideally, you should include the issue number in the commit message.
$ git commit -m "Issue #<issue-number> - <commit-message>"
Push your feature branch to your fork.
$ git push origin <feature-branch-name>
[Open a Pull Request](https://help.github.com/articles/using-pull-requests) against the upstream master branch.
Please give your pull request a clear title and description and note which issue(s) your pull request fixes.
- All linters should be happy (can be run with `make verify`).
- Every exported function should have [documentation](http://blog.golang.org/godoc-documenting-go-code) and corresponding [tests](http://golang.org/doc/code.html#Testing).
**Important:** By submitting a patch, you agree to allow the project owners to license your work under the [Apache 2.0 License](./LICENSE).
### Go Tools
For consistency and to catch minor issues for all of go code, please run `make verify`.
Many editors can execute the above on save.
---
Guidelines based on http://azkaban.github.io/contributing.html

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2014, OmniTI Computer Consulting, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,19 +0,0 @@
help: ## Print this help
@grep --no-filename -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sed 's/:.*## /·/' | sort | column -t -W 2 -s '·' -c $(shell tput cols)
all: test ## Run tests
-include rules.mk
-include lint.mk
test: ## Run tests
go test ./...
verify: gofumpt prettier lint ## Verify code style, is lint free, freshness ...
git diff | (! grep .)
fix: gofumpt-fix prettier-fix ## Fix code formatting errors
tools: ${toolsBins} ## Build Go based build tools
.PHONY: all help test tools verify

View File

@ -1,53 +0,0 @@
# Go Wrapper for ZFS
Simple wrappers for ZFS command line tools.
[![GoDoc](https://godoc.org/github.com/mistifyio/go-zfs?status.svg)](https://godoc.org/github.com/mistifyio/go-zfs)
## Requirements
You need a working ZFS setup. To use on Ubuntu 14.04, setup ZFS:
sudo apt-get install python-software-properties
sudo apt-add-repository ppa:zfs-native/stable
sudo apt-get update
sudo apt-get install ubuntu-zfs libzfs-dev
Developed using Go 1.3, but currently there isn't anything 1.3 specific. Don't use Ubuntu packages for Go, use http://golang.org/doc/install
Generally you need root privileges to use anything zfs related.
## Status
This has been only been tested on Ubuntu 14.04
In the future, we hope to work directly with libzfs.
# Hacking
The tests have decent examples for most functions.
```go
//assuming a zpool named test
//error handling omitted
f, err := zfs.CreateFilesystem("test/snapshot-test", nil)
ok(t, err)
s, err := f.Snapshot("test", nil)
ok(t, err)
// snapshot is named "test/snapshot-test@test"
c, err := s.Clone("test/clone-test", nil)
err := c.Destroy()
err := s.Destroy()
err := f.Destroy()
```
# Contributing
See the [contributing guidelines](./CONTRIBUTING.md)

View File

@ -1,33 +0,0 @@
GOVERSION = "1.17.8"
Vagrant.configure("2") do |config|
config.vm.define "ubuntu" do |ubuntu|
ubuntu.vm.box = "generic/ubuntu2004"
end
config.vm.define "freebsd" do |freebsd|
freebsd.vm.box = "generic/freebsd13"
end
config.ssh.forward_agent = true
config.vm.synced_folder ".", "/home/vagrant/go/src/github.com/mistifyio/go-zfs", create: true
config.vm.provision "shell", inline: <<-EOF
set -euxo pipefail
os=$(uname -s|tr '[A-Z]' '[a-z]')
case $os in
linux) apt-get update -y && apt-get install -y --no-install-recommends gcc libc-dev zfsutils-linux ;;
esac
cd /tmp
curl -fLO --retry-max-time 30 --retry 10 https://go.dev/dl/go#{GOVERSION}.$os-amd64.tar.gz
tar -C /usr/local -zxf go#{GOVERSION}.$os-amd64.tar.gz
ln -nsf /usr/local/go/bin/go /usr/local/bin/go
rm -rf go*.tar.gz
chown -R vagrant:vagrant /home/vagrant/go
cd /home/vagrant/go/src/github.com/mistifyio/go-zfs
go test -c
sudo ./go-zfs.test -test.v
CGO_ENABLED=0 go test -c
sudo ./go-zfs.test -test.v
EOF
end

View File

@ -1,18 +0,0 @@
package zfs
import (
"fmt"
)
// Error is an error which is returned when the `zfs` or `zpool` shell
// commands return with a non-zero exit code.
type Error struct {
Err error
Debug string
Stderr string
}
// Error returns the string representation of an Error.
func (e Error) Error() string {
return fmt.Sprintf("%s: %q => %s", e.Err, e.Debug, e.Stderr)
}

View File

@ -1,75 +0,0 @@
# BEGIN: lint-install -makefile lint.mk .
# http://github.com/tinkerbell/lint-install
.PHONY: lint
lint: _lint
LINT_ARCH := $(shell uname -m)
LINT_OS := $(shell uname)
LINT_OS_LOWER := $(shell echo $(LINT_OS) | tr '[:upper:]' '[:lower:]')
LINT_ROOT := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
# shellcheck and hadolint lack arm64 native binaries: rely on x86-64 emulation
ifeq ($(LINT_OS),Darwin)
ifeq ($(LINT_ARCH),arm64)
LINT_ARCH=x86_64
endif
endif
LINTERS :=
FIXERS :=
SHELLCHECK_VERSION ?= v0.8.0
SHELLCHECK_BIN := out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)
$(SHELLCHECK_BIN):
mkdir -p out/linters
rm -rf out/linters/shellcheck-*
curl -sSfL https://github.com/koalaman/shellcheck/releases/download/$(SHELLCHECK_VERSION)/shellcheck-$(SHELLCHECK_VERSION).$(LINT_OS_LOWER).$(LINT_ARCH).tar.xz | tar -C out/linters -xJf -
mv out/linters/shellcheck-$(SHELLCHECK_VERSION)/shellcheck $@
rm -rf out/linters/shellcheck-$(SHELLCHECK_VERSION)/shellcheck
LINTERS += shellcheck-lint
shellcheck-lint: $(SHELLCHECK_BIN)
$(SHELLCHECK_BIN) $(shell find . -name "*.sh")
FIXERS += shellcheck-fix
shellcheck-fix: $(SHELLCHECK_BIN)
$(SHELLCHECK_BIN) $(shell find . -name "*.sh") -f diff | { read -t 1 line || exit 0; { echo "$$line" && cat; } | git apply -p2; }
GOLANGCI_LINT_CONFIG := $(LINT_ROOT)/.golangci.yml
GOLANGCI_LINT_VERSION ?= v1.43.0
GOLANGCI_LINT_BIN := out/linters/golangci-lint-$(GOLANGCI_LINT_VERSION)-$(LINT_ARCH)
$(GOLANGCI_LINT_BIN):
mkdir -p out/linters
rm -rf out/linters/golangci-lint-*
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b out/linters $(GOLANGCI_LINT_VERSION)
mv out/linters/golangci-lint $@
LINTERS += golangci-lint-lint
golangci-lint-lint: $(GOLANGCI_LINT_BIN)
find . -name go.mod -execdir "$(GOLANGCI_LINT_BIN)" run -c "$(GOLINT_CONFIG)" \;
FIXERS += golangci-lint-fix
golangci-lint-fix: $(GOLANGCI_LINT_BIN)
find . -name go.mod -execdir "$(GOLANGCI_LINT_BIN)" run -c "$(GOLINT_CONFIG)" --fix \;
YAMLLINT_VERSION ?= 1.26.3
YAMLLINT_ROOT := out/linters/yamllint-$(YAMLLINT_VERSION)
YAMLLINT_BIN := $(YAMLLINT_ROOT)/dist/bin/yamllint
$(YAMLLINT_BIN):
mkdir -p out/linters
rm -rf out/linters/yamllint-*
curl -sSfL https://github.com/adrienverge/yamllint/archive/refs/tags/v$(YAMLLINT_VERSION).tar.gz | tar -C out/linters -zxf -
cd $(YAMLLINT_ROOT) && pip3 install --target dist .
LINTERS += yamllint-lint
yamllint-lint: $(YAMLLINT_BIN)
PYTHONPATH=$(YAMLLINT_ROOT)/dist $(YAMLLINT_ROOT)/dist/bin/yamllint .
.PHONY: _lint $(LINTERS)
_lint: $(LINTERS)
.PHONY: fix $(FIXERS)
fix: $(FIXERS)
# END: lint-install -makefile lint.mk .

View File

@ -1,49 +0,0 @@
# Only use the recipes defined in these makefiles
MAKEFLAGS += --no-builtin-rules
.SUFFIXES:
# Delete target files if there's an error
# This avoids a failure to then skip building on next run if the output is created by shell redirection for example
# Not really necessary for now, but just good to have already if it becomes necessary later.
.DELETE_ON_ERROR:
# Treat the whole recipe as a one shell script/invocation instead of one-per-line
.ONESHELL:
# Use bash instead of plain sh
SHELL := bash
.SHELLFLAGS := -o pipefail -euc
version := $(shell git rev-parse --short HEAD)
tag := $(shell git tag --points-at HEAD)
ifneq (,$(tag))
version := $(tag)-$(version)
endif
LDFLAGS := -ldflags "-X main.version=$(version)"
export CGO_ENABLED := 0
ifeq ($(origin GOBIN), undefined)
GOBIN := ${PWD}/bin
export GOBIN
PATH := ${GOBIN}:${PATH}
export PATH
endif
toolsBins := $(addprefix bin/,$(notdir $(shell grep '^\s*_' tooling/tools.go | awk -F'"' '{print $$2}')))
# installs cli tools defined in tools.go
$(toolsBins): tooling/go.mod tooling/go.sum tooling/tools.go
$(toolsBins): CMD=$(shell awk -F'"' '/$(@F)"/ {print $$2}' tooling/tools.go)
$(toolsBins):
cd tooling && go install $(CMD)
.PHONY: gofumpt
gofumpt: bin/gofumpt
gofumpt -s -d .
gofumpt-fix: bin/gofumpt
gofumpt -s -w .
.PHONY: prettier prettier-fix
prettier:
prettier --list-different --ignore-path .gitignore .
prettier-fix:
prettier --write --ignore-path .gitignore .

View File

@ -1,26 +0,0 @@
let _pkgs = import <nixpkgs> { };
in { pkgs ? import (_pkgs.fetchFromGitHub {
owner = "NixOS";
repo = "nixpkgs";
#branch@date: 21.11@2022-02-13
rev = "560ad8a2f89586ab1a14290f128ad6a393046065";
sha256 = "0s0dv1clfpjyzy4p6ywxvzmwx9ddbr2yl77jf1wqdbr0x1206hb8";
}) { } }:
with pkgs;
mkShell {
buildInputs = [
git
gnumake
gnused
go
nixfmt
nodePackages.prettier
python3Packages.pip
python3Packages.setuptools
rufo
shfmt
vagrant
];
}

View File

@ -1,357 +0,0 @@
package zfs
import (
"bytes"
"errors"
"fmt"
"io"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/google/uuid"
)
type command struct {
Command string
Stdin io.Reader
Stdout io.Writer
}
func (c *command) Run(arg ...string) ([][]string, error) {
cmd := exec.Command(c.Command, arg...)
var stdout, stderr bytes.Buffer
if c.Stdout == nil {
cmd.Stdout = &stdout
} else {
cmd.Stdout = c.Stdout
}
if c.Stdin != nil {
cmd.Stdin = c.Stdin
}
cmd.Stderr = &stderr
id := uuid.New().String()
joinedArgs := cmd.Path
if len(cmd.Args) > 1 {
joinedArgs = strings.Join(append([]string{cmd.Path}, cmd.Args[1:]...), " ")
}
logger.Log([]string{"ID:" + id, "START", joinedArgs})
if err := cmd.Run(); err != nil {
return nil, &Error{
Err: err,
Debug: joinedArgs,
Stderr: stderr.String(),
}
}
logger.Log([]string{"ID:" + id, "FINISH"})
// assume if you passed in something for stdout, that you know what to do with it
if c.Stdout != nil {
return nil, nil
}
lines := strings.Split(stdout.String(), "\n")
// last line is always blank
lines = lines[0 : len(lines)-1]
output := make([][]string, len(lines))
for i, l := range lines {
output[i] = strings.Split(l, "\t")
}
return output, nil
}
func setString(field *string, value string) {
v := ""
if value != "-" {
v = value
}
*field = v
}
func setUint(field *uint64, value string) error {
var v uint64
if value != "-" {
var err error
v, err = strconv.ParseUint(value, 10, 64)
if err != nil {
return err
}
}
*field = v
return nil
}
func (d *Dataset) parseLine(line []string) error {
var err error
if len(line) != len(dsPropList) {
return errors.New("output does not match what is expected on this platform")
}
setString(&d.Name, line[0])
setString(&d.Origin, line[1])
if err = setUint(&d.Used, line[2]); err != nil {
return err
}
if err = setUint(&d.Avail, line[3]); err != nil {
return err
}
setString(&d.Mountpoint, line[4])
setString(&d.Compression, line[5])
setString(&d.Type, line[6])
if err = setUint(&d.Volsize, line[7]); err != nil {
return err
}
if err = setUint(&d.Quota, line[8]); err != nil {
return err
}
if err = setUint(&d.Referenced, line[9]); err != nil {
return err
}
if runtime.GOOS == "solaris" {
return nil
}
if err = setUint(&d.Written, line[10]); err != nil {
return err
}
if err = setUint(&d.Logicalused, line[11]); err != nil {
return err
}
return setUint(&d.Usedbydataset, line[12])
}
/*
* from zfs diff`s escape function:
*
* Prints a file name out a character at a time. If the character is
* not in the range of what we consider "printable" ASCII, display it
* as an escaped 3-digit octal value. ASCII values less than a space
* are all control characters and we declare the upper end as the
* DELete character. This also is the last 7-bit ASCII character.
* We choose to treat all 8-bit ASCII as not printable for this
* application.
*/
func unescapeFilepath(path string) (string, error) {
buf := make([]byte, 0, len(path))
llen := len(path)
for i := 0; i < llen; {
if path[i] == '\\' {
if llen < i+4 {
return "", fmt.Errorf("invalid octal code: too short")
}
octalCode := path[(i + 1):(i + 4)]
val, err := strconv.ParseUint(octalCode, 8, 8)
if err != nil {
return "", fmt.Errorf("invalid octal code: %w", err)
}
buf = append(buf, byte(val))
i += 4
} else {
buf = append(buf, path[i])
i++
}
}
return string(buf), nil
}
var changeTypeMap = map[string]ChangeType{
"-": Removed,
"+": Created,
"M": Modified,
"R": Renamed,
}
var inodeTypeMap = map[string]InodeType{
"B": BlockDevice,
"C": CharacterDevice,
"/": Directory,
">": Door,
"|": NamedPipe,
"@": SymbolicLink,
"P": EventPort,
"=": Socket,
"F": File,
}
// matches (+1) or (-1).
var referenceCountRegex = regexp.MustCompile(`\(([+-]\d+?)\)`)
func parseReferenceCount(field string) (int, error) {
matches := referenceCountRegex.FindStringSubmatch(field)
if matches == nil {
return 0, fmt.Errorf("regexp does not match")
}
return strconv.Atoi(matches[1])
}
func parseInodeChange(line []string) (*InodeChange, error) {
llen := len(line) // nolint:ifshort // llen *is* actually used
if llen < 1 {
return nil, fmt.Errorf("empty line passed")
}
changeType := changeTypeMap[line[0]]
if changeType == 0 {
return nil, fmt.Errorf("unknown change type '%s'", line[0])
}
switch changeType {
case Renamed:
if llen != 4 {
return nil, fmt.Errorf("mismatching number of fields: expect 4, got: %d", llen)
}
case Modified:
if llen != 4 && llen != 3 {
return nil, fmt.Errorf("mismatching number of fields: expect 3..4, got: %d", llen)
}
default:
if llen != 3 {
return nil, fmt.Errorf("mismatching number of fields: expect 3, got: %d", llen)
}
}
inodeType := inodeTypeMap[line[1]]
if inodeType == 0 {
return nil, fmt.Errorf("unknown inode type '%s'", line[1])
}
path, err := unescapeFilepath(line[2])
if err != nil {
return nil, fmt.Errorf("failed to parse filename: %w", err)
}
var newPath string
var referenceCount int
switch changeType {
case Renamed:
newPath, err = unescapeFilepath(line[3])
if err != nil {
return nil, fmt.Errorf("failed to parse filename: %w", err)
}
case Modified:
if llen == 4 {
referenceCount, err = parseReferenceCount(line[3])
if err != nil {
return nil, fmt.Errorf("failed to parse reference count: %w", err)
}
}
default:
newPath = ""
}
return &InodeChange{
Change: changeType,
Type: inodeType,
Path: path,
NewPath: newPath,
ReferenceCountChange: referenceCount,
}, nil
}
// example input for parseInodeChanges
// M / /testpool/bar/
// + F /testpool/bar/hello.txt
// M / /testpool/bar/hello.txt (+1)
// M / /testpool/bar/hello-hardlink
func parseInodeChanges(lines [][]string) ([]*InodeChange, error) {
changes := make([]*InodeChange, len(lines))
for i, line := range lines {
c, err := parseInodeChange(line)
if err != nil {
return nil, fmt.Errorf("failed to parse line %d of zfs diff: %w, got: '%s'", i, err, line)
}
changes[i] = c
}
return changes, nil
}
func listByType(t, filter string) ([]*Dataset, error) {
args := []string{"list", "-rHp", "-t", t, "-o", dsPropListOptions}
if filter != "" {
args = append(args, filter)
}
out, err := zfsOutput(args...)
if err != nil {
return nil, err
}
var datasets []*Dataset
name := ""
var ds *Dataset
for _, line := range out {
if name != line[0] {
name = line[0]
ds = &Dataset{Name: name}
datasets = append(datasets, ds)
}
if err := ds.parseLine(line); err != nil {
return nil, err
}
}
return datasets, nil
}
func propsSlice(properties map[string]string) []string {
args := make([]string, 0, len(properties)*3)
for k, v := range properties {
args = append(args, "-o")
args = append(args, fmt.Sprintf("%s=%s", k, v))
}
return args
}
func (z *Zpool) parseLine(line []string) error {
prop := line[1]
val := line[2]
var err error
switch prop {
case "name":
setString(&z.Name, val)
case "health":
setString(&z.Health, val)
case "allocated":
err = setUint(&z.Allocated, val)
case "size":
err = setUint(&z.Size, val)
case "free":
err = setUint(&z.Free, val)
case "fragmentation":
// Trim trailing "%" before parsing uint
i := strings.Index(val, "%")
if i < 0 {
i = len(val)
}
err = setUint(&z.Fragmentation, val[:i])
case "readonly":
z.ReadOnly = val == "on"
case "freeing":
err = setUint(&z.Freeing, val)
case "leaked":
err = setUint(&z.Leaked, val)
case "dedupratio":
// Trim trailing "x" before parsing float64
z.DedupRatio, err = strconv.ParseFloat(val[:len(val)-1], 64)
}
return err
}

View File

@ -1,19 +0,0 @@
//go:build !solaris
// +build !solaris
package zfs
import "strings"
var (
// List of ZFS properties to retrieve from zfs list command on a non-Solaris platform.
dsPropList = []string{"name", "origin", "used", "available", "mountpoint", "compression", "type", "volsize", "quota", "referenced", "written", "logicalused", "usedbydataset"}
dsPropListOptions = strings.Join(dsPropList, ",")
// List of Zpool properties to retrieve from zpool list command on a non-Solaris platform.
zpoolPropList = []string{"name", "health", "allocated", "size", "free", "readonly", "dedupratio", "fragmentation", "freeing", "leaked"}
zpoolPropListOptions = strings.Join(zpoolPropList, ",")
zpoolArgs = []string{"get", "-Hp", zpoolPropListOptions}
)

View File

@ -1,19 +0,0 @@
//go:build solaris
// +build solaris
package zfs
import "strings"
var (
// List of ZFS properties to retrieve from zfs list command on a Solaris platform
dsPropList = []string{"name", "origin", "used", "available", "mountpoint", "compression", "type", "volsize", "quota", "referenced"}
dsPropListOptions = strings.Join(dsPropList, ",")
// List of Zpool properties to retrieve from zpool list command on a non-Solaris platform
zpoolPropList = []string{"name", "health", "allocated", "size", "free", "readonly", "dedupratio"}
zpoolPropListOptions = strings.Join(zpoolPropList, ",")
zpoolArgs = []string{"get", "-Hp", zpoolPropListOptions}
)

View File

@ -1,449 +0,0 @@
// Package zfs provides wrappers around the ZFS command line tools.
package zfs
import (
"errors"
"fmt"
"io"
"strconv"
"strings"
)
// ZFS dataset types, which can indicate if a dataset is a filesystem, snapshot, or volume.
const (
DatasetFilesystem = "filesystem"
DatasetSnapshot = "snapshot"
DatasetVolume = "volume"
)
// Dataset is a ZFS dataset. A dataset could be a clone, filesystem, snapshot, or volume.
// The Type struct member can be used to determine a dataset's type.
//
// The field definitions can be found in the ZFS manual:
// https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
type Dataset struct {
Name string
Origin string
Used uint64
Avail uint64
Mountpoint string
Compression string
Type string
Written uint64
Volsize uint64
Logicalused uint64
Usedbydataset uint64
Quota uint64
Referenced uint64
}
// InodeType is the type of inode as reported by Diff.
type InodeType int
// Types of Inodes.
const (
_ = iota // 0 == unknown type
BlockDevice InodeType = iota
CharacterDevice
Directory
Door
NamedPipe
SymbolicLink
EventPort
Socket
File
)
// ChangeType is the type of inode change as reported by Diff.
type ChangeType int
// Types of Changes.
const (
_ = iota // 0 == unknown type
Removed ChangeType = iota
Created
Modified
Renamed
)
// DestroyFlag is the options flag passed to Destroy.
type DestroyFlag int
// Valid destroy options.
const (
DestroyDefault DestroyFlag = 1 << iota
DestroyRecursive = 1 << iota
DestroyRecursiveClones = 1 << iota
DestroyDeferDeletion = 1 << iota
DestroyForceUmount = 1 << iota
)
// InodeChange represents a change as reported by Diff.
type InodeChange struct {
Change ChangeType
Type InodeType
Path string
NewPath string
ReferenceCountChange int
}
// Logger can be used to log commands/actions.
type Logger interface {
Log(cmd []string)
}
type defaultLogger struct{}
func (*defaultLogger) Log([]string) {
}
var logger Logger = &defaultLogger{}
// SetLogger set a log handler to log all commands including arguments before they are executed.
func SetLogger(l Logger) {
if l != nil {
logger = l
}
}
// zfs is a helper function to wrap typical calls to zfs that ignores stdout.
func zfs(arg ...string) error {
_, err := zfsOutput(arg...)
return err
}
// zfs is a helper function to wrap typical calls to zfs.
func zfsOutput(arg ...string) ([][]string, error) {
c := command{Command: "zfs"}
return c.Run(arg...)
}
// Datasets returns a slice of ZFS datasets, regardless of type.
// A filter argument may be passed to select a dataset with the matching name, or empty string ("") may be used to select all datasets.
func Datasets(filter string) ([]*Dataset, error) {
return listByType("all", filter)
}
// Snapshots returns a slice of ZFS snapshots.
// A filter argument may be passed to select a snapshot with the matching name, or empty string ("") may be used to select all snapshots.
func Snapshots(filter string) ([]*Dataset, error) {
return listByType(DatasetSnapshot, filter)
}
// Filesystems returns a slice of ZFS filesystems.
// A filter argument may be passed to select a filesystem with the matching name, or empty string ("") may be used to select all filesystems.
func Filesystems(filter string) ([]*Dataset, error) {
return listByType(DatasetFilesystem, filter)
}
// Volumes returns a slice of ZFS volumes.
// A filter argument may be passed to select a volume with the matching name, or empty string ("") may be used to select all volumes.
func Volumes(filter string) ([]*Dataset, error) {
return listByType(DatasetVolume, filter)
}
// GetDataset retrieves a single ZFS dataset by name.
// This dataset could be any valid ZFS dataset type, such as a clone, filesystem, snapshot, or volume.
func GetDataset(name string) (*Dataset, error) {
out, err := zfsOutput("list", "-Hp", "-o", dsPropListOptions, name)
if err != nil {
return nil, err
}
ds := &Dataset{Name: name}
for _, line := range out {
if err := ds.parseLine(line); err != nil {
return nil, err
}
}
return ds, nil
}
// Clone clones a ZFS snapshot and returns a clone dataset.
// An error will be returned if the input dataset is not of snapshot type.
func (d *Dataset) Clone(dest string, properties map[string]string) (*Dataset, error) {
if d.Type != DatasetSnapshot {
return nil, errors.New("can only clone snapshots")
}
args := make([]string, 2, 4)
args[0] = "clone"
args[1] = "-p"
if properties != nil {
args = append(args, propsSlice(properties)...)
}
args = append(args, []string{d.Name, dest}...)
if err := zfs(args...); err != nil {
return nil, err
}
return GetDataset(dest)
}
// Unmount unmounts currently mounted ZFS file systems.
func (d *Dataset) Unmount(force bool) (*Dataset, error) {
if d.Type == DatasetSnapshot {
return nil, errors.New("cannot unmount snapshots")
}
args := make([]string, 1, 3)
args[0] = "umount"
if force {
args = append(args, "-f")
}
args = append(args, d.Name)
if err := zfs(args...); err != nil {
return nil, err
}
return GetDataset(d.Name)
}
// Mount mounts ZFS file systems.
func (d *Dataset) Mount(overlay bool, options []string) (*Dataset, error) {
if d.Type == DatasetSnapshot {
return nil, errors.New("cannot mount snapshots")
}
args := make([]string, 1, 5)
args[0] = "mount"
if overlay {
args = append(args, "-O")
}
if options != nil {
args = append(args, "-o")
args = append(args, strings.Join(options, ","))
}
args = append(args, d.Name)
if err := zfs(args...); err != nil {
return nil, err
}
return GetDataset(d.Name)
}
// ReceiveSnapshot receives a ZFS stream from the input io.Reader.
// A new snapshot is created with the specified name, and streams the input data into the newly-created snapshot.
func ReceiveSnapshot(input io.Reader, name string) (*Dataset, error) {
c := command{Command: "zfs", Stdin: input}
if _, err := c.Run("receive", name); err != nil {
return nil, err
}
return GetDataset(name)
}
// SendSnapshot sends a ZFS stream of a snapshot to the input io.Writer.
// An error will be returned if the input dataset is not of snapshot type.
func (d *Dataset) SendSnapshot(output io.Writer) error {
if d.Type != DatasetSnapshot {
return errors.New("can only send snapshots")
}
c := command{Command: "zfs", Stdout: output}
_, err := c.Run("send", d.Name)
return err
}
// IncrementalSend sends a ZFS stream of a snapshot to the input io.Writer using the baseSnapshot as the starting point.
// An error will be returned if the input dataset is not of snapshot type.
func (d *Dataset) IncrementalSend(baseSnapshot *Dataset, output io.Writer) error {
if d.Type != DatasetSnapshot || baseSnapshot.Type != DatasetSnapshot {
return errors.New("can only send snapshots")
}
c := command{Command: "zfs", Stdout: output}
_, err := c.Run("send", "-i", baseSnapshot.Name, d.Name)
return err
}
// CreateVolume creates a new ZFS volume with the specified name, size, and properties.
//
// A full list of available ZFS properties may be found in the ZFS manual:
// https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
func CreateVolume(name string, size uint64, properties map[string]string) (*Dataset, error) {
args := make([]string, 4, 5)
args[0] = "create"
args[1] = "-p"
args[2] = "-V"
args[3] = strconv.FormatUint(size, 10)
if properties != nil {
args = append(args, propsSlice(properties)...)
}
args = append(args, name)
if err := zfs(args...); err != nil {
return nil, err
}
return GetDataset(name)
}
// Destroy destroys a ZFS dataset.
// If the destroy bit flag is set, any descendents of the dataset will be recursively destroyed, including snapshots.
// If the deferred bit flag is set, the snapshot is marked for deferred deletion.
func (d *Dataset) Destroy(flags DestroyFlag) error {
args := make([]string, 1, 3)
args[0] = "destroy"
if flags&DestroyRecursive != 0 {
args = append(args, "-r")
}
if flags&DestroyRecursiveClones != 0 {
args = append(args, "-R")
}
if flags&DestroyDeferDeletion != 0 {
args = append(args, "-d")
}
if flags&DestroyForceUmount != 0 {
args = append(args, "-f")
}
args = append(args, d.Name)
err := zfs(args...)
return err
}
// SetProperty sets a ZFS property on the receiving dataset.
//
// A full list of available ZFS properties may be found in the ZFS manual:
// https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
func (d *Dataset) SetProperty(key, val string) error {
prop := strings.Join([]string{key, val}, "=")
err := zfs("set", prop, d.Name)
return err
}
// GetProperty returns the current value of a ZFS property from the receiving dataset.
//
// A full list of available ZFS properties may be found in the ZFS manual:
// https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
func (d *Dataset) GetProperty(key string) (string, error) {
out, err := zfsOutput("get", "-H", key, d.Name)
if err != nil {
return "", err
}
return out[0][2], nil
}
// Rename renames a dataset.
func (d *Dataset) Rename(name string, createParent, recursiveRenameSnapshots bool) (*Dataset, error) {
args := make([]string, 3, 5)
args[0] = "rename"
args[1] = d.Name
args[2] = name
if createParent {
args = append(args, "-p")
}
if recursiveRenameSnapshots {
args = append(args, "-r")
}
if err := zfs(args...); err != nil {
return d, err
}
return GetDataset(name)
}
// Snapshots returns a slice of all ZFS snapshots of a given dataset.
func (d *Dataset) Snapshots() ([]*Dataset, error) {
return Snapshots(d.Name)
}
// CreateFilesystem creates a new ZFS filesystem with the specified name and properties.
//
// A full list of available ZFS properties may be found in the ZFS manual:
// https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
func CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {
args := make([]string, 1, 4)
args[0] = "create"
if properties != nil {
args = append(args, propsSlice(properties)...)
}
args = append(args, name)
if err := zfs(args...); err != nil {
return nil, err
}
return GetDataset(name)
}
// Snapshot creates a new ZFS snapshot of the receiving dataset, using the specified name.
// Optionally, the snapshot can be taken recursively, creating snapshots of all descendent filesystems in a single, atomic operation.
func (d *Dataset) Snapshot(name string, recursive bool) (*Dataset, error) {
args := make([]string, 1, 4)
args[0] = "snapshot"
if recursive {
args = append(args, "-r")
}
snapName := fmt.Sprintf("%s@%s", d.Name, name)
args = append(args, snapName)
if err := zfs(args...); err != nil {
return nil, err
}
return GetDataset(snapName)
}
// Rollback rolls back the receiving ZFS dataset to a previous snapshot.
// Optionally, intermediate snapshots can be destroyed.
// A ZFS snapshot rollback cannot be completed without this option, if more recent snapshots exist.
// An error will be returned if the input dataset is not of snapshot type.
func (d *Dataset) Rollback(destroyMoreRecent bool) error {
if d.Type != DatasetSnapshot {
return errors.New("can only rollback snapshots")
}
args := make([]string, 1, 3)
args[0] = "rollback"
if destroyMoreRecent {
args = append(args, "-r")
}
args = append(args, d.Name)
err := zfs(args...)
return err
}
// Children returns a slice of children of the receiving ZFS dataset.
// A recursion depth may be specified, or a depth of 0 allows unlimited recursion.
func (d *Dataset) Children(depth uint64) ([]*Dataset, error) {
args := []string{"list"}
if depth > 0 {
args = append(args, "-d")
args = append(args, strconv.FormatUint(depth, 10))
} else {
args = append(args, "-r")
}
args = append(args, "-t", "all", "-Hp", "-o", dsPropListOptions)
args = append(args, d.Name)
out, err := zfsOutput(args...)
if err != nil {
return nil, err
}
var datasets []*Dataset
name := ""
var ds *Dataset
for _, line := range out {
if name != line[0] {
name = line[0]
ds = &Dataset{Name: name}
datasets = append(datasets, ds)
}
if err := ds.parseLine(line); err != nil {
return nil, err
}
}
return datasets[1:], nil
}
// Diff returns changes between a snapshot and the given ZFS dataset.
// The snapshot name must include the filesystem part as it is possible to compare clones with their origin snapshots.
func (d *Dataset) Diff(snapshot string) ([]*InodeChange, error) {
args := []string{"diff", "-FH", snapshot, d.Name}
out, err := zfsOutput(args...)
if err != nil {
return nil, err
}
inodeChanges, err := parseInodeChanges(out)
if err != nil {
return nil, err
}
return inodeChanges, nil
}

View File

@ -1,116 +0,0 @@
package zfs
// ZFS zpool states, which can indicate if a pool is online, offline, degraded, etc.
//
// More information regarding zpool states can be found in the ZFS manual:
// https://openzfs.github.io/openzfs-docs/man/7/zpoolconcepts.7.html#Device_Failure_and_Recovery
const (
ZpoolOnline = "ONLINE"
ZpoolDegraded = "DEGRADED"
ZpoolFaulted = "FAULTED"
ZpoolOffline = "OFFLINE"
ZpoolUnavail = "UNAVAIL"
ZpoolRemoved = "REMOVED"
)
// Zpool is a ZFS zpool.
// A pool is a top-level structure in ZFS, and can contain many descendent datasets.
type Zpool struct {
Name string
Health string
Allocated uint64
Size uint64
Free uint64
Fragmentation uint64
ReadOnly bool
Freeing uint64
Leaked uint64
DedupRatio float64
}
// zpool is a helper function to wrap typical calls to zpool and ignores stdout.
func zpool(arg ...string) error {
_, err := zpoolOutput(arg...)
return err
}
// zpool is a helper function to wrap typical calls to zpool.
func zpoolOutput(arg ...string) ([][]string, error) {
c := command{Command: "zpool"}
return c.Run(arg...)
}
// GetZpool retrieves a single ZFS zpool by name.
func GetZpool(name string) (*Zpool, error) {
args := zpoolArgs
args = append(args, name)
out, err := zpoolOutput(args...)
if err != nil {
return nil, err
}
z := &Zpool{Name: name}
for _, line := range out {
if err := z.parseLine(line); err != nil {
return nil, err
}
}
return z, nil
}
// Datasets returns a slice of all ZFS datasets in a zpool.
func (z *Zpool) Datasets() ([]*Dataset, error) {
return Datasets(z.Name)
}
// Snapshots returns a slice of all ZFS snapshots in a zpool.
func (z *Zpool) Snapshots() ([]*Dataset, error) {
return Snapshots(z.Name)
}
// CreateZpool creates a new ZFS zpool with the specified name, properties, and optional arguments.
//
// A full list of available ZFS properties and command-line arguments may be found in the ZFS manual:
// https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
// https://openzfs.github.io/openzfs-docs/man/8/zpool-create.8.html
func CreateZpool(name string, properties map[string]string, args ...string) (*Zpool, error) {
cli := make([]string, 1, 4)
cli[0] = "create"
if properties != nil {
cli = append(cli, propsSlice(properties)...)
}
cli = append(cli, name)
cli = append(cli, args...)
if err := zpool(cli...); err != nil {
return nil, err
}
return &Zpool{Name: name}, nil
}
// Destroy destroys a ZFS zpool by name.
func (z *Zpool) Destroy() error {
err := zpool("destroy", z.Name)
return err
}
// ListZpools list all ZFS zpools accessible on the current system.
func ListZpools() ([]*Zpool, error) {
args := []string{"list", "-Ho", "name"}
out, err := zpoolOutput(args...)
if err != nil {
return nil, err
}
var pools []*Zpool
for _, line := range out {
z, err := GetZpool(line[0])
if err != nil {
return nil, err
}
pools = append(pools, z)
}
return pools, nil
}

7
vendor/modules.txt vendored
View File

@ -151,10 +151,6 @@ github.com/containerd/typeurl
# github.com/containerd/typeurl/v2 v2.1.1 # github.com/containerd/typeurl/v2 v2.1.1
## explicit; go 1.13 ## explicit; go 1.13
github.com/containerd/typeurl/v2 github.com/containerd/typeurl/v2
# github.com/containerd/zfs v1.2.0
## explicit; go 1.19
github.com/containerd/zfs
github.com/containerd/zfs/plugin
# github.com/containernetworking/cni v1.1.2 # github.com/containernetworking/cni v1.1.2
## explicit; go 1.14 ## explicit; go 1.14
github.com/containernetworking/cni/libcni github.com/containernetworking/cni/libcni
@ -307,9 +303,6 @@ github.com/miekg/pkcs11
# github.com/minio/sha256-simd v1.0.1 # github.com/minio/sha256-simd v1.0.1
## explicit; go 1.17 ## explicit; go 1.17
github.com/minio/sha256-simd github.com/minio/sha256-simd
# github.com/mistifyio/go-zfs/v3 v3.0.1
## explicit; go 1.14
github.com/mistifyio/go-zfs/v3
# github.com/moby/locker v1.0.1 # github.com/moby/locker v1.0.1
## explicit; go 1.13 ## explicit; go 1.13
github.com/moby/locker github.com/moby/locker