2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.md.sal.dom.xsql;
11 import java.io.FileOutputStream;
12 import java.io.InputStream;
13 import java.io.PrintStream;
14 import java.net.ServerSocket;
15 import java.net.Socket;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Calendar;
19 import java.util.LinkedList;
20 import java.util.List;
23 import java.util.concurrent.ConcurrentHashMap;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
28 import org.opendaylight.controller.md.sal.dom.xsql.jdbc.JDBCResultSet;
29 import org.opendaylight.controller.md.sal.dom.xsql.jdbc.JDBCServer;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.model.api.Module;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
35 * @author Sharon Aicler(saichler@gmail.com)
37 public class XSQLAdapter extends Thread implements SchemaContextListener {
39 private static final int SLEEP = 10000;
40 private static XSQLAdapter a = new XSQLAdapter();
41 private static PrintStream l = null;
42 private static String tmpDir = null;
43 private static File xqlLog = null;
44 public boolean stopped = false;
45 private List<String> elementHosts = new ArrayList<String>();
46 private String username;
47 private String password;
48 private String transport = "tcp";
49 private int reconnectTimeout;
52 private String applicationName = "NQL Adapter";
53 private Map<String, NEEntry> elements = new ConcurrentHashMap<String, XSQLAdapter.NEEntry>();
54 private StringBuffer lastInputString = new StringBuffer();
55 private XSQLBluePrint bluePrint = new XSQLBluePrint();
56 private boolean toCsv = false;
57 private String exportToFileName = null;
58 private XSQLThreadPool threadPool = new XSQLThreadPool(1, "Tasks", 2000);
59 private JDBCServer jdbcServer = new JDBCServer(this);
60 private String pinningFile;
61 private ServerSocket serverSocket = null;
62 private DOMDataBroker domDataBroker = null;
63 private static final String REFERENCE_FIELD_NAME = "reference";
65 private XSQLAdapter() {
66 XSQLAdapter.log("Starting Adapter");
69 serverSocket = new ServerSocket(34343);
70 } catch (Exception err) {
74 XSQLAdapter.log("Adapter Started!");
78 public void loadBluePrint(){
80 InputStream in = this.getClass().getClassLoader().getResourceAsStream("BluePrintCache.dat");
82 this.bluePrint = XSQLBluePrint.load(in);
85 }catch(Exception err){
86 err.printStackTrace();
90 public static XSQLAdapter getInstance() {
94 public static File getXQLLogfile() {
95 tmpDir = System.getProperty("java.io.tmpdir");
96 xqlLog = new File(tmpDir + "/xql.log");
100 public static void main(String args[]) {
101 XSQLAdapter adapter = new XSQLAdapter();
105 public static void log(String str) {
108 synchronized (XSQLAdapter.class) {
111 new FileOutputStream(getXQLLogfile()));
115 l.print(Calendar.getInstance().getTime());
118 } catch (Exception err) {
119 err.printStackTrace();
123 public static void log(Exception e) {
126 synchronized (XSQLAdapter.class) {
129 new FileOutputStream(getXQLLogfile()));
133 l.print(Calendar.getInstance().getTime());
135 e.printStackTrace(l);
136 } catch (Exception err) {
137 err.printStackTrace();
142 public void onGlobalContextUpdated(SchemaContext context) {
143 Set<Module> modules = context.getModules();
144 for (Module m : modules) {
145 if (XSQLODLUtils.createOpenDaylightCache(this.bluePrint, m)) {
146 this.addRootElement(m);
151 public void setDataBroker(DOMDataBroker ddb) {
152 this.domDataBroker = ddb;
155 public XSQLBluePrint getBluePrint() {
156 return this.bluePrint;
159 public List<Object> collectModuleRoots(XSQLBluePrintNode table,LogicalDatastoreType type) {
160 if (table.getParent().isModule()) {
162 List<Object> result = new LinkedList<Object>();
163 YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier
165 .node(XSQLODLUtils.getPath(table.getFirstFromSchemaNodes()).get(0))
167 DOMDataReadTransaction t = this.domDataBroker
168 .newReadOnlyTransaction();
169 Object node = t.read(type,
170 instanceIdentifier).get();
172 node = XSQLODLUtils.get(node, REFERENCE_FIELD_NAME);
178 } catch (Exception err) {
179 XSQLAdapter.log(err);
182 return collectModuleRoots(table.getParent(),type);
187 public void execute(JDBCResultSet rs) {
188 if(this.domDataBroker==null){
189 rs.setFinished(true);
192 List<XSQLBluePrintNode> tables = rs.getTables();
193 List<Object> roots = collectModuleRoots(tables.get(0),LogicalDatastoreType.OPERATIONAL);
194 roots.addAll(collectModuleRoots(tables.get(0),LogicalDatastoreType.CONFIGURATION));
196 rs.setFinished(true);
198 XSQLBluePrintNode main = rs.getMainTable();
199 List<NETask> tasks = new LinkedList<XSQLAdapter.NETask>();
201 for (Object entry : roots) {
202 NETask task = new NETask(rs, entry, main, bluePrint);
206 for (NETask task : tasks) {
207 threadPool.addTask(task);
214 Socket s = serverSocket.accept();
215 new TelnetConnection(s);
216 } catch (Exception err) {
217 err.printStackTrace();
220 } catch (Exception err2) {
227 public void addRootElement(Object o) {
228 NEEntry entry = new NEEntry(o);
229 elements.put(o.toString(), entry);
233 public void processCommand(StringBuffer inputString, PrintStream sout) {
234 if (inputString.toString().trim().equals("r")) {
235 sout.println(lastInputString);
236 inputString = lastInputString;
238 lastInputString = inputString;
239 String input = inputString.toString().trim();
240 if (input.startsWith("setExcel")) {
241 String substr = input.substring("setExcel".length()).trim();
242 if (!substr.equals("")) {
243 // excelPath01 = substr;
245 // sout.println("Excel Path="+excelPath01);
246 } else if (input.startsWith("list vrel")) {
247 String substr = input.substring("list vrel".length()).trim();
248 XSQLBluePrintNode node = bluePrint
249 .getBluePrintNodeByTableName(substr);
251 sout.println("Unknown Interface " + substr);
254 List<String> fld = new ArrayList<String>();
255 for (XSQLBluePrintRelation r : node.getRelations()) {
256 fld.add(r.toString());
258 String p[] = (String[]) fld.toArray(new String[fld.size()]);
260 for (int i = 0; i < p.length; i++) {
263 } else if (input.startsWith("list vfields")) {
264 String substr = input.substring("list vfields".length()).trim();
265 XSQLBluePrintNode node = bluePrint
266 .getBluePrintNodeByTableName(substr);
268 sout.println("Unknown Interface " + substr);
271 List<String> fld = new ArrayList<String>();
272 for (XSQLColumn c : node.getColumns()) {
273 fld.add(c.getName());
275 String p[] = (String[]) fld.toArray(new String[fld.size()]);
277 for (int i = 0; i < p.length; i++) {
280 } else if (input.startsWith("jdbc")) {
281 String addr = input.substring(5).trim();
282 jdbcServer.connectToClient(addr);
283 sout.println("Connected To " + addr);
284 } else if (input.startsWith("fetch")) {
285 // fetchSize = Integer.parseInt(input.substring(6).trim());
286 } else if (input.startsWith("list vtables")) {
288 String iNames[] = bluePrint.getAllTableNames().toArray(
292 for (int i = 0; i < iNames.length; i++) {
293 sout.println(iNames[i]);
295 } else if (input.equals("help") || input.equals("?")) {
296 // sout.println(getLongDescription());
297 } else if (input.equals("avmdata")) {
299 // myConnection.getManagedData();
300 } catch (Exception err) {
302 } else if (input.equals("innerjoin")) {
303 // innerJoin = !innerJoin;
304 // sout.println("Inner Join set to "+innerJoin);
305 } else if (input.equals("exit")) {
308 } catch (Exception err) {
310 } else if (input.equals("save")) {
311 XSQLBluePrint.save(this.bluePrint);
312 } else if (input.equals("tocsv")) {
314 sout.println("to csv file is " + toCsv);
315 } else if (input.indexOf("filename") != -1) {
316 exportToFileName = input.substring(input.indexOf(" ")).trim();
317 sout.println("Exporting to file:" + exportToFileName);
318 } else if (!input.equals("")) {
320 if (exportToFileName != null) {
322 PrintStream o = new PrintStream(new File(
324 executeSql(inputString.toString(), o);
326 } catch (Exception err) {
327 err.printStackTrace();
331 String fName = "export-" + System.currentTimeMillis()
333 PrintStream o = new PrintStream(new File(fName));
334 executeSql(inputString.toString(), o);
336 sout.println("Exported to file " + fName);
337 } catch (Exception err) {
338 err.printStackTrace();
343 executeSql(inputString.toString(), sout);
349 public void executeSql(String sql, PrintStream out) {
350 JDBCResultSet rs = new JDBCResultSet(sql);
353 JDBCServer.execute(rs, this);
354 boolean isFirst = true;
355 int loc = rs.getFields().size() - 1;
357 for (XSQLColumn c : rs.getFields()) {
369 out.print(c.getName());
372 int cw = c.getCharWidth();
373 int cnw = c.getName().length();
378 for (int i = 0; i < gap; i++) {
383 totalWidth += c.getCharWidth() + 1;
398 for (int i = 0; i < totalWidth; i++) {
406 loc = rs.getFields().size() - 1;
407 for (XSQLColumn c : rs.getFields()) {
419 Object sValue = rs.getObject(c.toString());
420 if (sValue == null) {
425 int cw = c.getCharWidth();
426 int vw = sValue.toString().length();
428 for (int i = 0; i < gap; i++) {
446 out.println("Total Number Of Records=" + count);
447 } catch (Exception err) {
448 err.printStackTrace(out);
452 public static class NETask implements Runnable {
454 private JDBCResultSet rs = null;
455 private Object modelRoot = null;
456 private XSQLBluePrintNode main = null;
457 private XSQLBluePrint bluePrint = null;
459 public NETask(JDBCResultSet _rs, Object _modelRoot,
460 XSQLBluePrintNode _main, XSQLBluePrint _bluePrint) {
462 this.modelRoot = _modelRoot;
464 this.bluePrint = _bluePrint;
468 rs.addRecords(modelRoot, main, true, main.getBluePrintNodeName(),
472 if (rs.numberOfTasks == 0) {
473 rs.setFinished(true);
480 private static class NEEntry {
481 private Object ne = null;
483 public NEEntry(Object _ne) {
487 public String toString() {
488 Module m = (Module) ne;
489 return m.getName() + " [" + m.getNamespace().toString() + "]";
493 private class TelnetConnection extends Thread {
495 private Socket socket = null;
496 private InputStream in = null;
497 private PrintStream out = null;
498 private Module currentModule = null;
500 public TelnetConnection(Socket s) {
503 this.in = s.getInputStream();
504 this.out = new PrintStream(s.getOutputStream());
506 } catch (Exception err) {
507 XSQLAdapter.log(err);
512 StringBuffer inputString = new StringBuffer();
513 String prompt = "XSQL>";
516 if (currentModule != null) {
517 prompt = "XQL/" + currentModule.getName() + ">";
521 byte data[] = new byte[1];
522 while (!socket.isClosed() && socket.isConnected() && !socket.isInputShutdown() && c != '\n') {
526 inputString.append(c);
527 } catch (Exception err) {
528 err.printStackTrace(out);
534 processCommand(inputString, out);
535 inputString = new StringBuffer();
537 } catch (Exception err) {
540 } catch (Exception err2) {