summaryrefslogtreecommitdiffstats
path: root/src/org.gluster.storage.management.gateway/src/org/gluster/storage/management/gateway/tasks/InitServerTask.java
blob: 4426683fd4861e63d19dd174c7a7b37cf88f3a3b (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
/*******************************************************************************
 * Copyright (c) 2006-2011 Gluster, Inc. <http://www.gluster.com>
 * This file is part of Gluster Management Gateway.
 *
 * Gluster Management Gateway is free software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * Gluster Management Gateway is distributed in the hope that it
 * will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 *******************************************************************************/
package org.gluster.storage.management.gateway.tasks;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.derby.tools.ij;
import org.gluster.storage.management.core.constants.CoreConstants;
import org.gluster.storage.management.core.exceptions.GlusterRuntimeException;
import org.gluster.storage.management.gateway.data.ClusterInfo;
import org.gluster.storage.management.gateway.data.PersistenceDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;


/**
 * Initializes the Gluster Management Server.
 */
public class InitServerTask extends JdbcDaoSupport {
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private SaltSource saltSource;
	
	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private String appVersion;

	@Autowired
	private PersistenceDao<ClusterInfo> clusterDao;

	@Autowired
	ServletContext servletContext;

	private static final String SCRIPT_DIR = "data/scripts/";

	public void securePasswords() {
		getJdbcTemplate().query("select username, password from users", new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String username = rs.getString(1);
				String password = rs.getString(2);
				UserDetails user = userDetailsService.loadUserByUsername(username);
				
				String encodedPassword = passwordEncoder.encodePassword(password, saltSource.getSalt(user));
				getJdbcTemplate().update("update users set password = ? where username = ?", encodedPassword, username);
				logger.debug("Updating password for username: " + username);
			}
		});
	}

	private void executeScript(File script) {
		ByteArrayOutputStream sqlOut = new ByteArrayOutputStream();
		int numOfExceptions;
		try {
			numOfExceptions = ij.runScript(getJdbcTemplate().getDataSource().getConnection(), new FileInputStream(
					script), CoreConstants.ENCODING_UTF8, sqlOut, CoreConstants.ENCODING_UTF8);
			String output = sqlOut.toString();
			sqlOut.close();
			logger.debug("Data script [" + script.getName() + "] returned with exit status [" + numOfExceptions
					+ "] and output [" + output + "]");
			if (numOfExceptions != 0) {
				throw new GlusterRuntimeException("Server data initialization script [ " + script.getName()
						+ "] failed with [" + numOfExceptions + "] exceptions! [" + output + "]");
			}
		} catch (Exception ex) {
			throw new GlusterRuntimeException("Server data initialization script [" + script.getName() + "] failed!",
					ex);
		}
	}

	private void initDatabase() {
		logger.info("Initializing server data...");
		executeScriptsFrom(getDirFromRelativePath(SCRIPT_DIR + appVersion));

		securePasswords(); // encrypt the passwords
	}

	private File getDirFromRelativePath(String relativePath) {
		String scriptDirPath = servletContext.getRealPath(relativePath);
		File scriptDir = new File(scriptDirPath);
		return scriptDir;
	}

	private void executeScriptsFrom(File scriptDir) {
		if (!scriptDir.exists()) {
			throw new GlusterRuntimeException("Script directory [" + scriptDir.getAbsolutePath() + "] doesn't exist!");
		}
		
		List<File> scripts = Arrays.asList(scriptDir.listFiles());
		if(scripts.size() == 0) {
			throw new GlusterRuntimeException("Script directory [" + scriptDir.getAbsolutePath() + "] is empty!");
		}
		
		Collections.sort(scripts);
		for (File script : scripts) {
			executeScript(script);
		}
	}

	/**
	 * Initializes the server database, if running for the first time.
	 */
	public synchronized void initServer() {
		try {
			String dbVersion = getDBVersion();
			if (!appVersion.equals(dbVersion)) {
				logger.info("App version [" + appVersion + "] differs from data version [" + dbVersion
						+ "]. Trying to upgrade data...");
				upgradeData(dbVersion, appVersion);
			}
		} catch (Exception ex) {
			logger.info("No cluster created yet. DB version query failed with error [" + ex.getMessage() + "]", ex);
			// Database not created yet. Create it!
			initDatabase();
		}
	}

	private void upgradeData(String fromVersion, String toVersion) {
		executeScriptsFrom(getDirFromRelativePath(SCRIPT_DIR + fromVersion + "-" + toVersion));
	}

	private String getDBVersion() {
		return (String) clusterDao.getSingleResultFromSQL("select version from version");
	}
}