1/*
2   Copyright The containerd Authors.
3
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15*/
16
17package ioutil
18
19import (
20	"errors"
21	"io"
22	"sync"
23)
24
25// WriterGroup is a group of writers. Writer could be dynamically
26// added and removed.
27type WriterGroup struct {
28	mu      sync.Mutex
29	writers map[string]io.WriteCloser
30	closed  bool
31}
32
33var _ io.Writer = &WriterGroup{}
34
35// NewWriterGroup creates an empty writer group.
36func NewWriterGroup() *WriterGroup {
37	return &WriterGroup{
38		writers: make(map[string]io.WriteCloser),
39	}
40}
41
42// Add adds a writer into the group. The writer will be closed
43// if the writer group is closed.
44func (g *WriterGroup) Add(key string, w io.WriteCloser) {
45	g.mu.Lock()
46	defer g.mu.Unlock()
47	if g.closed {
48		w.Close()
49		return
50	}
51	g.writers[key] = w
52}
53
54// Get gets a writer from the group, returns nil if the writer
55// doesn't exist.
56func (g *WriterGroup) Get(key string) io.WriteCloser {
57	g.mu.Lock()
58	defer g.mu.Unlock()
59	return g.writers[key]
60}
61
62// Remove removes a writer from the group.
63func (g *WriterGroup) Remove(key string) {
64	g.mu.Lock()
65	defer g.mu.Unlock()
66	w, ok := g.writers[key]
67	if !ok {
68		return
69	}
70	w.Close()
71	delete(g.writers, key)
72}
73
74// Write writes data into each writer. If a writer returns error,
75// it will be closed and removed from the writer group. It returns
76// error if writer group is empty.
77func (g *WriterGroup) Write(p []byte) (int, error) {
78	g.mu.Lock()
79	defer g.mu.Unlock()
80	for k, w := range g.writers {
81		n, err := w.Write(p)
82		if err == nil && len(p) == n {
83			continue
84		}
85		// The writer is closed or in bad state, remove it.
86		w.Close()
87		delete(g.writers, k)
88	}
89	if len(g.writers) == 0 {
90		return 0, errors.New("writer group is empty")
91	}
92	return len(p), nil
93}
94
95// Close closes the writer group. Write will return error after
96// closed.
97func (g *WriterGroup) Close() {
98	g.mu.Lock()
99	defer g.mu.Unlock()
100	for _, w := range g.writers {
101		w.Close()
102	}
103	g.writers = nil
104	g.closed = true
105}
106