summaryrefslogtreecommitdiffstats
path: root/infra/translate-utils/src/main/java/io/fd/honeycomb/translate/util/read/KeepaliveReaderWrapper.java
blob: f8d1458c0dec8c6e34ff6b3adbfd14cebc87cb79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*
 * Copyright (c) 2016 Cisco and/or its affiliates.
 *
 * 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 io.fd.honeycomb.translate.util.read;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import io.fd.honeycomb.translate.read.ReadContext;
import io.fd.honeycomb.translate.read.Reader;
import io.fd.honeycomb.translate.MappingContext;
import io.fd.honeycomb.translate.ModificationCache;
import io.fd.honeycomb.translate.read.ReadFailedException;
import java.io.Closeable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.concepts.Builder;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Reader wrapper that periodically invokes a read to determine whether reads are still fully functional.
 * In case a specific error occurs, Keep-alive failure listener gets notified.
 */
public final class KeepaliveReaderWrapper<D extends DataObject, B extends Builder<D>> implements Reader<D, B>, Runnable, Closeable {

    private static final Logger LOG = LoggerFactory.getLogger(KeepaliveReaderWrapper.class);

    private static final NoopReadContext CTX = new NoopReadContext();

    private final Reader<D, B> delegate;
    private final Class<? extends Exception> exceptionType;
    private final KeepaliveFailureListener failureListener;
    private final ScheduledFuture<?> scheduledFuture;

    /**
     * Create new Keepalive wrapper
     *
     * @param delegate underlying reader performing actual reads
     * @param executor scheduled executor service to schedule keepalive calls
     * @param exception type of exception used to differentiate keepalive exception from other exceptions
     * @param delayInSeconds number of seconds to wait between keepalive calls
     * @param failureListener listener to be called whenever a keepalive failure is detected
     */
    public KeepaliveReaderWrapper(@Nonnull final Reader<D, B> delegate,
                                  @Nonnull final ScheduledExecutorService executor,
                                  @Nonnull final Class<? extends Exception> exception,
                                  @Nonnegative final int delayInSeconds,
                                  @Nonnull final KeepaliveFailureListener failureListener) {
        this.delegate = delegate;
        this.exceptionType = exception;
        this.failureListener = failureListener;
        Preconditions.checkArgument(delayInSeconds > 0, "Delay cannot be < 0");
        LOG.debug("Starting keep-alive execution on top of: {} with delay of: {} seconds", delegate, delayInSeconds);
        scheduledFuture = executor.scheduleWithFixedDelay(this, delayInSeconds, delayInSeconds, TimeUnit.SECONDS);
    }

    @Nonnull
    public Optional<? extends DataObject> read(@Nonnull final InstanceIdentifier id,
                                               @Nonnull final ReadContext ctx) throws ReadFailedException {
        return delegate.read(id, ctx);
    }

    public void readCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
                                      @Nonnull final B builder,
                                      @Nonnull final ReadContext ctx) throws ReadFailedException {
        delegate.readCurrentAttributes(id, builder, ctx);
    }

    @Nonnull
    public B getBuilder(final InstanceIdentifier<D> id) {
        return delegate.getBuilder(id);
    }

    public void merge(@Nonnull final Builder<? extends DataObject> parentBuilder,
                      @Nonnull final D readValue) {
        delegate.merge(parentBuilder, readValue);
    }

    @Nonnull
    @Override
    public InstanceIdentifier<D> getManagedDataObjectType() {
        return delegate.getManagedDataObjectType();
    }

    @Override
    public void run() {
        LOG.trace("Invoking keepalive");
        try {
            final Optional<? extends DataObject> read = read(delegate.getManagedDataObjectType(), CTX);
            LOG.debug("Keepalive executed successfully with data: {}", read);
        } catch (Exception e) {
            if (exceptionType.isAssignableFrom(e.getClass())) {
                LOG.warn("Keepalive failed. Notifying listener", e);
                failureListener.onKeepaliveFailure();
            }
            LOG.warn("Keepalive failed unexpectedly", e);
            throw new IllegalArgumentException("Unexpected failure during keep-alive execution", e);
        }
    }

    @Override
    public void close() {
        // Do not interrupt, it's not our executor
        scheduledFuture.cancel(false);
    }

    /**
     * Listener that gets called whenever keepalive fails as expected
     */
    public interface KeepaliveFailureListener {

        void onKeepaliveFailure();
    }

    private static final class NoopMappingContext implements MappingContext {
        @Override
        public <T extends DataObject> Optional<T> read(@Nonnull final InstanceIdentifier<T> currentId) {
            return Optional.absent();
        }

        @Override
        public void delete(final InstanceIdentifier<?> path) {}

        @Override
        public <T extends DataObject> void merge(final InstanceIdentifier<T> path, final T data) {}

        @Override
        public <T extends DataObject> void put(final InstanceIdentifier<T> path, final T data) {}

        @Override
        public void close() {}
    }

    private static class NoopReadContext implements ReadContext {

        private final ModificationCache modificationCache = new ModificationCache();

        @Nonnull
        @Override
        public ModificationCache getModificationCache() {
            return modificationCache;
        }

        @Nonnull
        @Override
        public MappingContext getMappingContext() {
            return new NoopMappingContext();
        }

        @Override
        public void close() {

        }
    }
}