Skip to content

Commit

Permalink
don't wait forever for the iptables lock
Browse files Browse the repository at this point in the history
if iptables version supports wait, we use `-w` without any additional
argument, so it keeps waiting forever trying to acquire the lock
at a 1 second interval rate.

This can cause issues on busy environments by software that depends
on this library, because they can be waiting forever.

We can make the timeout configurable, just only for iptables versions
that have the --wait flag.

Signed-off-by: Antonio Ojea <[email protected]>
  • Loading branch information
aojea authored and Antonio Ojea committed Jul 8, 2020
1 parent 521ee6c commit 37774f2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
15 changes: 15 additions & 0 deletions iptables/iptables.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ type IPTables struct {
v2 int
v3 int
mode string // the underlying iptables operating mode, e.g. nf_tables
timeout int // time to wait for the iptables lock, default is 0, that means wait forever
}

// Stat represents a structured statistic entry.
Expand Down Expand Up @@ -132,6 +133,17 @@ func (ipt *IPTables) Proto() Protocol {
return ipt.proto
}

// Timeout returns the timeout used by this IPTables.
func (ipt *IPTables) Timeout() int {
return ipt.timeout
}

// SetTimeout sets the timeout used by this IPTables.
// 0 means wait forever
func (ipt *IPTables) SetTimeout(timeout int) {
ipt.timeout = timeout
}

// Exists checks if given rulespec in specified table/chain exists
func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {
if !ipt.hasCheck {
Expand Down Expand Up @@ -426,6 +438,9 @@ func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
args = append([]string{ipt.path}, args...)
if ipt.hasWait {
args = append(args, "--wait")
if ipt.timeout != 0 {
args = append(args, strconv.Itoa(ipt.timeout))
}
} else {
fmu, err := newXtablesFileLock()
if err != nil {
Expand Down
16 changes: 16 additions & 0 deletions iptables/iptables_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,22 @@ func TestProto(t *testing.T) {
}
}

func TestTimeout(t *testing.T) {
ipt, err := New()
if err != nil {
t.Fatalf("New failed: %v", err)
}
if ipt.Timeout() != 0 {
t.Fatalf("Expected timeout 0 (wait forever), got %v", ipt.Timeout())
}

ipt.SetTimeout(5)
if ipt.Timeout() != 5 {
t.Fatalf("Expected timeout 5, got %v", ipt.Timeout())
}

}

func randChain(t *testing.T) string {
n, err := rand.Int(rand.Reader, big.NewInt(1000000))
if err != nil {
Expand Down

0 comments on commit 37774f2

Please sign in to comment.