5b8803001ca9a33f71d2cacab990f03891a6891e
[controller.git] / opendaylight / netconf / netconf-ssh / src / main / java / org / opendaylight / controller / netconf / ssh / osgi / NetconfSSHActivator.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.netconf.ssh.osgi;
9
10 import com.google.common.base.Optional;
11 import org.apache.commons.io.IOUtils;
12 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
13 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
14 import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator;
15 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
16 import org.opendaylight.controller.usermanager.IUserManager;
17 import org.osgi.framework.BundleActivator;
18 import org.osgi.framework.BundleContext;
19 import org.osgi.framework.ServiceReference;
20 import org.osgi.util.tracker.ServiceTracker;
21 import org.osgi.util.tracker.ServiceTrackerCustomizer;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.net.InetSocketAddress;
29
30 /**
31  * Activator for netconf SSH bundle which creates SSH bridge between netconf client and netconf server. Activator
32  * starts SSH Server in its own thread. This thread is closed when activator calls stop() method. Server opens socket
33  * and listen for client connections. Each client connection creation is handled in separate
34  * {@link org.opendaylight.controller.netconf.ssh.threads.SocketThread} thread.
35  * This thread creates two additional threads {@link org.opendaylight.controller.netconf.ssh.threads.IOThread}
36  * forwarding data from/to client.IOThread closes servers session and server connection when it gets -1 on input stream.
37  * {@link org.opendaylight.controller.netconf.ssh.threads.IOThread}'s run method waits for -1 on input stream to finish.
38  * All threads are daemons.
39  **/
40 public class NetconfSSHActivator implements BundleActivator{
41
42     private NetconfSSHServer server;
43     private static final Logger logger =  LoggerFactory.getLogger(NetconfSSHActivator.class);
44     private static final String EXCEPTION_MESSAGE = "Netconf ssh bridge is not available.";
45     private IUserManager iUserManager;
46     private BundleContext context = null;
47
48     private ServiceTrackerCustomizer<IUserManager, IUserManager> customizer = new ServiceTrackerCustomizer<IUserManager, IUserManager>(){
49         @Override
50         public IUserManager addingService(ServiceReference<IUserManager> reference) {
51             logger.trace("Service {} added, let there be SSH bridge.", reference);
52             iUserManager =  context.getService(reference);
53             try {
54                 onUserManagerFound(iUserManager);
55             } catch (Exception e) {
56                 logger.trace("Can't start SSH server due to {}",e);
57             }
58             return iUserManager;
59         }
60         @Override
61         public void modifiedService(ServiceReference<IUserManager> reference, IUserManager service) {
62             logger.trace("Replacing modified service {} in netconf SSH.", reference);
63             server.addUserManagerService(service);
64         }
65         @Override
66         public void removedService(ServiceReference<IUserManager> reference, IUserManager service) {
67             logger.trace("Removing service {} from netconf SSH. " +
68                     "SSH won't authenticate users until IUserManager service will be started.", reference);
69             removeUserManagerService();
70         }
71     };
72
73
74     @Override
75     public void start(BundleContext context)  {
76         this.context = context;
77         listenForManagerService();
78     }
79
80     @Override
81     public void stop(BundleContext context) throws IOException {
82         if (server != null){
83             server.stop();
84             logger.trace("Netconf SSH bridge is down ...");
85         }
86     }
87     private void startSSHServer() throws IllegalStateException, IOException {
88         logger.trace("Starting netconf SSH  bridge.");
89         Optional<InetSocketAddress> sshSocketAddressOptional = NetconfConfigUtil.extractSSHNetconfAddress(context, EXCEPTION_MESSAGE);
90         InetSocketAddress tcpSocketAddress = NetconfConfigUtil.extractTCPNetconfAddress(context,
91                 EXCEPTION_MESSAGE, true);
92
93         if (sshSocketAddressOptional.isPresent()){
94             String path = NetconfConfigUtil.getPrivateKeyPath(context);
95             path = path.replace("\\", "/");  // FIXME: shouldn't this convert lines to system dependent path separator?
96             if (path.equals("")){
97                 throw new IllegalStateException("Missing netconf.ssh.pk.path key in configuration file.");
98             }
99
100             File privateKeyFile = new File(path);
101             String privateKeyPEMString = null;
102             if (privateKeyFile.exists() == false) {
103                 // generate & save to file
104                 try {
105                     privateKeyPEMString = PEMGenerator.generateTo(privateKeyFile);
106                 } catch (Exception e) {
107                     logger.error("Exception occured while generating PEM string {}",e);
108                 }
109             } else {
110                 // read from file
111                 try (FileInputStream fis = new FileInputStream(path)) {
112                     privateKeyPEMString = IOUtils.toString(fis);
113                 } catch (IOException e) {
114                     logger.error("Error reading RSA key from file '{}'", path);
115                     throw new IllegalStateException("Error reading RSA key from file " + path);
116                 }
117             }
118             AuthProvider authProvider = null;
119             try {
120                 authProvider = new AuthProvider(iUserManager, privateKeyPEMString);
121             } catch (Exception e) {
122                 logger.error("Error instantiating AuthProvider {}",e);
123             }
124             this.server = NetconfSSHServer.start(sshSocketAddressOptional.get().getPort(),tcpSocketAddress,authProvider);
125
126             Thread serverThread = new  Thread(server,"netconf SSH server thread");
127             serverThread.setDaemon(true);
128             serverThread.start();
129             logger.trace("Netconf SSH  bridge up and running.");
130         } else {
131             logger.trace("No valid connection configuration for SSH bridge found.");
132             throw new IllegalStateException("No valid connection configuration for SSH bridge found.");
133         }
134     }
135     private void onUserManagerFound(IUserManager userManager) throws IOException {
136         if (server!=null && server.isUp()){
137            server.addUserManagerService(userManager);
138         } else {
139            startSSHServer();
140         }
141     }
142     private void removeUserManagerService(){
143         this.server.removeUserManagerService();
144     }
145     private void listenForManagerService(){
146         ServiceTracker<IUserManager, IUserManager> listenerTracker = new ServiceTracker<>(context, IUserManager.class,customizer);
147         listenerTracker.open();
148     }
149 }