aboutsummaryrefslogtreecommitdiffstats
path: root/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt
blob: 694756195ece8ef58bf4c6ca9befdf2e5fa5b0d8 (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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
 * Copyright © 2017-2019 AT&T, Bell Canada
 *
 * 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 org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.core

import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo
import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfReceivedEvent
import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfSessionListener
import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils
import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.RpcMessageUtils
import org.slf4j.LoggerFactory
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.nio.charset.StandardCharsets
import java.util.concurrent.CompletableFuture

class NetconfDeviceCommunicator(private var inputStream: InputStream,
                                private var out: OutputStream,
                                private val deviceInfo: DeviceInfo,
                                private val sessionListener: NetconfSessionListener,
                                private var replies: MutableMap<String, CompletableFuture<String>>) : Thread() {

    private val log = LoggerFactory.getLogger(NetconfDeviceCommunicator::class.java)
    private var state = NetconfMessageState.NO_MATCHING_PATTERN

    init {
        start()
    }

    override fun run() {
        var bufferReader: BufferedReader? = null
        while (bufferReader == null) {
            bufferReader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
        }

        try {
            var socketClosed = false
            val deviceReplyBuilder = StringBuilder()
            while (!socketClosed) {
                val cInt = bufferReader.read()
                if (cInt == -1) {
                    log.error("$deviceInfo: Received cInt = -1")
//                    bufferReader.close()
                    socketClosed = true
//                    sessionListener.notify(NetconfReceivedEvent(
//                        NetconfReceivedEvent.Type.SESSION_CLOSED,
//                        deviceInfo = deviceInfo))
                }
                val c = cInt.toChar()
                state = state.evaluateChar(c)
                deviceReplyBuilder.append(c)
                if (state === NetconfMessageState.END_PATTERN) {
                    var deviceReply = deviceReplyBuilder.toString()
                    if (deviceReply == RpcMessageUtils.END_PATTERN) {
                        socketClosed = true
                        bufferReader.close()
                        sessionListener.notify(NetconfReceivedEvent(
                            NetconfReceivedEvent.Type.DEVICE_UNREGISTERED,
                            deviceInfo = deviceInfo))
                    } else {
                        deviceReply = deviceReply.replace(RpcMessageUtils.END_PATTERN, "")
                        receivedMessage(deviceReply)
                        deviceReplyBuilder.setLength(0)
                    }
                } else if (state === NetconfMessageState.END_CHUNKED_PATTERN) {
                    var deviceReply = deviceReplyBuilder.toString()
                    if (!NetconfMessageUtils.validateChunkedFraming(deviceReply)) {
                        log.debug("$deviceInfo: Received badly framed message $deviceReply")
                        socketClosed = true
                        sessionListener.notify(NetconfReceivedEvent(
                            NetconfReceivedEvent.Type.DEVICE_ERROR,
                            deviceInfo = deviceInfo))
                    } else {
                        deviceReply = deviceReply.replace(RpcMessageUtils.MSGLEN_REGEX_PATTERN.toRegex(), "")
                        deviceReply = deviceReply.replace(NetconfMessageUtils.CHUNKED_END_REGEX_PATTERN.toRegex(), "")
                        receivedMessage(deviceReply)
                        deviceReplyBuilder.setLength(0)
                    }
                }
            }

        } catch (e: IOException) {
            log.warn("$deviceInfo: Fail while reading from channel", e)
            sessionListener.notify(NetconfReceivedEvent(
                NetconfReceivedEvent.Type.DEVICE_ERROR,
                deviceInfo = deviceInfo))
        }

    }

    private enum class NetconfMessageState {
        NO_MATCHING_PATTERN {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == ']') {
                    FIRST_BRACKET
                } else if (c == '\n') {
                    FIRST_LF
                } else {
                    this
                }
            }
        },
        FIRST_BRACKET {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == ']') {
                    SECOND_BRACKET
                } else {
                    NO_MATCHING_PATTERN
                }
            }
        },
        SECOND_BRACKET {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == '>') {
                    FIRST_BIGGER
                } else {
                    NO_MATCHING_PATTERN
                }
            }
        },
        FIRST_BIGGER {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == ']') {
                    THIRD_BRACKET
                } else {
                    NO_MATCHING_PATTERN
                }
            }
        },
        THIRD_BRACKET {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == ']') {
                    ENDING_BIGGER
                } else {
                    NO_MATCHING_PATTERN
                }
            }
        },
        ENDING_BIGGER {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == '>') {
                    END_PATTERN
                } else {
                    NO_MATCHING_PATTERN
                }
            }
        },
        FIRST_LF {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == '#') {
                    FIRST_HASH
                } else if (c == ']') {
                    FIRST_BRACKET
                } else if (c == '\n') {
                    this
                } else {
                    NO_MATCHING_PATTERN
                }
            }
        },
        FIRST_HASH {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == '#') {
                    SECOND_HASH
                } else {
                    NO_MATCHING_PATTERN
                }
            }
        },
        SECOND_HASH {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return if (c == '\n') {
                    END_CHUNKED_PATTERN
                } else {
                    NO_MATCHING_PATTERN
                }
            }
        },
        END_CHUNKED_PATTERN {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return NO_MATCHING_PATTERN
            }
        },
        END_PATTERN {
            override fun evaluateChar(c: Char): NetconfMessageState {
                return NO_MATCHING_PATTERN
            }
        };

        internal abstract fun evaluateChar(c: Char): NetconfMessageState
    }

    fun sendMessage(request: String, messageId: String): CompletableFuture<String> {
        log.info("$deviceInfo: Sending message: \n $request")
        val future = CompletableFuture<String>()
        replies.put(messageId, future)
        val outputStream = OutputStreamWriter(out, StandardCharsets.UTF_8)
        synchronized(this) {
            try {
                outputStream.write(request)
                outputStream.flush()
            } catch (e: IOException) {
                log.error("$deviceInfo: Failed to send message : \n $request", e)
                future.completeExceptionally(e)
            }

        }
        return future
    }

    private fun receivedMessage(deviceReply: String) {
        if (deviceReply.contains(RpcMessageUtils.RPC_REPLY) || deviceReply.contains(RpcMessageUtils.RPC_ERROR)
            || deviceReply.contains(RpcMessageUtils.HELLO)) {
            log.info("$deviceInfo: Received message with messageId: {}  \n $deviceReply",
                NetconfMessageUtils.getMsgId(deviceReply))

        } else {
            log.error("$deviceInfo: Invalid message received: \n $deviceReply")
        }
        sessionListener.notify(NetconfReceivedEvent(
            NetconfReceivedEvent.Type.DEVICE_REPLY,
            deviceReply,
            NetconfMessageUtils.getMsgId(deviceReply),
            deviceInfo))
    }
}