blob: 88fadb365f27cb8a4f9e6baff6498598f705ca46 [file] [log] [blame]
susmit shannigrahi21009e32015-03-26 17:00:32 -06001#!/usr/bin/env python3
2# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
3#
4# Copyright (c) 2015, Colorado State University.
5#
6# This file is part of ndn-atmos.
7#
8# ndn-atmos is free software: you can redistribute it and/or modify it under the
9# terms of the GNU Lesser General Public License as published by the Free Software
10# Foundation, either version 3 of the License, or (at your option) any later version.
11#
12# ndn-atmos is distributed in the hope that it will be useful, but WITHOUT ANY
13# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
14# PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
15#
16# You should have received copies of the GNU General Public License and GNU Lesser
17# General Public License along with ndn-atmos, e.g., in COPYING.md file. If not, see
18# <http://www.gnu.org/licenses/>.
19#
20# See AUTHORS.md for complete list of ndn-atmos authors and contributors.
21
22'''This module is for inserting NDN names in underlying database'''
23
24import mysql.connector as sql
25from mysql.connector import errorcode
26import sys
27import getpass
28import hashlib
29from ndn_cmmap_translators import atmos_translator
30
31def createTables(cursor):
32 TABLES = {}
33 TABLES['cmip5'] = (
34 "CREATE TABLE `cmip5` ("
35 " `id` int(100) AUTO_INCREMENT NOT NULL,"
36 " `sha256` varchar(64) UNIQUE NOT NULL,"
37 " `name` varchar(1000) NOT NULL,"
38 " `activity` varchar(100) NOT NULL,"
39 " `product` varchar(100) NOT NULL,"
40 " `organization` varchar(100) NOT NULL,"
41 " `model` varchar(100) NOT NULL,"
42 " `experiment` varchar(100) NOT NULL,"
43 " `frequency` varchar(100) NOT NULL,"
44 " `modeling_realm` varchar(100) NOT NULL,"
45 " `variable_name` varchar(100) NOT NULL,"
46 " `ensemble` varchar(100) NOT NULL,"
47 " `time` varchar(100) NOT NULL,"
48 " PRIMARY KEY (`id`)"
49 ") ENGINE=InnoDB")
50
51 #check if tables exist, if not create them
52 #create tables per schema in the wiki
53 for tableName, query in TABLES.items():
54 try:
55 print("Creating table {}: ".format(tableName))
56 cursor.execute(query)
57 print("Created table {}: ".format(tableName))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060058 return True
susmit shannigrahi21009e32015-03-26 17:00:32 -060059 except sql.Error as err:
60 if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
61 print("Table already exists: %s " %(tableName))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060062 return True
susmit shannigrahi21009e32015-03-26 17:00:32 -060063 else:
64 print("Failed to create table: %s" %(err.msg))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060065 return False
susmit shannigrahi21009e32015-03-26 17:00:32 -060066
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060067def insertName(cursor, name):
susmit shannigrahi21009e32015-03-26 17:00:32 -060068 if __debug__:
69 print("Name to insert %s " %(name))
70
71 #hashvalue is needed since name is too long for primary key (must be <767 bytes)
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060072 hashValue = hashlib.sha256(str(name).encode('utf-8')).hexdigest()
susmit shannigrahi21009e32015-03-26 17:00:32 -060073 if __debug__:
74 print("Hash of name %s " %(hashValue))
75
76 ##NOTE:must use %s to prevent sql injection in all sql queries
77 splitName = list(filter(None, name.split("/")))
78 splitName.insert(0, hashValue)
79 splitName.insert(0, name)
80 splitName = tuple(splitName)
81 if __debug__:
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060082 print("Name to insert in database %s" %(splitName,))
susmit shannigrahi21009e32015-03-26 17:00:32 -060083
84 addRecord = ("INSERT INTO cmip5 "
85 "(name, sha256, activity, product, organization, model, experiment, frequency,\
86 modeling_realm, variable_name, ensemble, time) "
87 "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
88
89 try:
90 cursor.execute(addRecord, splitName)
91 print("Inserted record %s" %(name))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060092 return True
susmit shannigrahi21009e32015-03-26 17:00:32 -060093 except sql.Error as err:
94 print("Error inserting name %s" %(err.msg))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060095 return False
susmit shannigrahi21009e32015-03-26 17:00:32 -060096
97if __name__ == '__main__':
98 datafilePath = input("File/directory to translate: ")
99 configFilepath = input("Schema file path for the above file/directory: ")
100
101 #do the translation, the library should provide error messages, if any
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600102 ndnNames = atmos_translator.argsForTranslation(datafilePath, configFilepath)
susmit shannigrahi21009e32015-03-26 17:00:32 -0600103 if len(ndnNames) == 0:
104 print("No name returned from the translator, exiting.")
105 sys.exit(-1)
106 if __debug__:
107 print("Returned NDN names: %s" %(ndnNames))
108
109 #open connection to db
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600110 dbHost = input("Database Host?")
susmit shannigrahi21009e32015-03-26 17:00:32 -0600111 dbName = input("Database to store NDN names?")
112 dbUsername = input("Database username?")
113 dbPasswd = getpass.getpass("Database password?")
114
115 try:
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600116 con = sql.connect(user=dbUsername, database=dbName, password=dbPasswd, host=dbHost)
susmit shannigrahi21009e32015-03-26 17:00:32 -0600117 cursor = con.cursor()
118 if __debug__:
119 print("successfully connected to database")
120
121 #if tables do not exist, create tables
susmit shannigrahi21009e32015-03-26 17:00:32 -0600122 #if table already exists, or creation successful, continue
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600123 if createTables(cursor):
susmit shannigrahi21009e32015-03-26 17:00:32 -0600124 for ndnName in ndnNames:
125 #get list of files and insert into database
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600126 resInsertnames = insertName(cursor, ndnName)
susmit shannigrahi21009e32015-03-26 17:00:32 -0600127 if __debug__:
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600128 print("Return Code is %s for inserting name: %s" %(resInsertnames, ndnName))
susmit shannigrahi21009e32015-03-26 17:00:32 -0600129 con.commit()
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600130 else:
131 print("Error creating tables, exiting.")
132 sys.exit(-1)
133
susmit shannigrahi21009e32015-03-26 17:00:32 -0600134 except sql.Error as err:
135 if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
136 print("Incorrect username or password")
137 elif err.errno == errorcode.ER_BAD_DB_ERROR:
138 print("Database does not exist")
139 else:
140 print("Error connecting to Database: %s" %(err.msg))
141 finally:
142 con.close()
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600143