aboutsummaryrefslogtreecommitdiffstats
path: root/mdbc-server/src/main/java/org/onap/music/mdbc/StateManager.java
blob: 04ac789aa51754b7b7582f0d78fccd66e4cc40ed (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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
 * ============LICENSE_START====================================================
 * org.onap.music.mdbc
 * =============================================================================
 * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
 * =============================================================================
 * 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.
 * ============LICENSE_END======================================================
 */
package org.onap.music.mdbc;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.tuple.Pair;
import org.onap.music.exceptions.MDBCServiceException;
import org.onap.music.exceptions.QueryException;
import org.onap.music.logging.EELFLoggerDelegate;
import org.onap.music.logging.format.AppMessages;
import org.onap.music.logging.format.ErrorSeverity;
import org.onap.music.logging.format.ErrorTypes;
import org.onap.music.mdbc.mixins.DBInterface;
import org.onap.music.mdbc.mixins.MixinFactory;
import org.onap.music.mdbc.mixins.MusicInterface;
import org.onap.music.mdbc.mixins.MusicInterface.OwnershipReturn;
import org.onap.music.mdbc.ownership.OwnershipAndCheckpoint;
import org.onap.music.mdbc.tables.MriReference;
import org.onap.music.mdbc.tables.MusicTxDigestDaemon;
import org.onap.music.mdbc.tables.MusicTxDigestId;
import org.onap.music.mdbc.tables.TxCommitProgress;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * \TODO Implement an interface for the server logic and a factory 
 * @author Enrique Saurez
 */
public class StateManager {

	//\TODO We need to fix the auto-commit mode and multiple transactions with the same connection

	private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(StateManager.class);

	/**
	 * This is the interface used by all the MusicSqlManagers, 
	 * that are created by the MDBC Server 
	 * @see MusicInterface 
     */
    private MusicInterface musicInterface;
    /**
     * This is the Running Queries information table.
     * It mainly contains information about the entities 
     * that have being committed so far.
     */
    private TxCommitProgress transactionInfo;
    private Map<String,MdbcConnection> mdbcConnections;
    private String sqlDBName;
    private String sqlDBUrl;
    
    String musicmixin;
    String cassandraUrl;
    private Properties info;
    
    /** Identifier for this server instance */
    private String mdbcServerName;
    private Map<String,DatabasePartition> connectionRanges;//Each connection owns its own database partition
    private final Lock eventualLock  = new ReentrantLock();
    private Set<Range> eventualRanges;
    /** lock for warmupRanges */
    private final Lock warmupLock = new ReentrantLock();
    /** a set of ranges that should be periodically updated with latest information, if null all tables should be warmed up */
    private Set<Range> rangesToWarmup;
    /** map of transactions that have already been applied/updated in this sites SQL db */
    private Map<Range, Pair<MriReference, MusicTxDigestId>> alreadyApplied;
    private OwnershipAndCheckpoint ownAndCheck;
    private Thread txDaemon ;

    /**
     * For testing purposes only
     */
    @Deprecated
    public StateManager() {
    }
    
	public StateManager(String sqlDBUrl, Properties newInfo, String mdbcServerName, String sqlDBName) throws MDBCServiceException {
        this.sqlDBName = sqlDBName;
        this.sqlDBUrl = cleanSqlUrl(sqlDBUrl);
        this.info = new Properties();
        this.mdbcServerName = mdbcServerName;
    
        this.connectionRanges = new ConcurrentHashMap<>();
        this.transactionInfo = new TxCommitProgress();
        //\fixme this might not be used, delete?
        try {
			info.load(this.getClass().getClassLoader().getResourceAsStream("music.properties"));
			info.load(this.getClass().getClassLoader().getResourceAsStream("key.properties"));
			info.putAll(MDBCUtils.getMdbcProperties());
		} catch (IOException e) {
			logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
		}
		info.putAll(newInfo);
        cassandraUrl = info.getProperty(Configuration.KEY_CASSANDRA_URL, Configuration.CASSANDRA_URL_DEFAULT);
        musicmixin = info.getProperty(Configuration.KEY_MUSIC_MIXIN_NAME, Configuration.MUSIC_MIXIN_DEFAULT);
        
        String writeLocksOnly = info.getProperty(Configuration.KEY_WRITE_LOCKS_ONLY);
        MDBCUtils.writeLocksOnly = (writeLocksOnly==null) ? Configuration.WRITE_LOCK_ONLY_DEFAULT : Boolean.parseBoolean(writeLocksOnly);
        
        initMusic();
        initSqlDatabase();
        initTxDaemonThread();
        String t = info.getProperty(Configuration.KEY_OWNERSHIP_TIMEOUT);
        long timeout = (t == null) ? Configuration.DEFAULT_OWNERSHIP_TIMEOUT : Integer.parseInt(t);
        alreadyApplied = new ConcurrentHashMap<>();
        ownAndCheck = new OwnershipAndCheckpoint(alreadyApplied, timeout);
    }

    protected String cleanSqlUrl(String url){
	    if(url!=null) {
            url = url.trim();
            if (url.length() > 0 && url.charAt(url.length() - 1) == '/') {
                url= url.substring(0, url.length() - 1);
            }
        }
        return url;
    }

    protected void initTxDaemonThread(){
        txDaemon = new Thread(
            new MusicTxDigestDaemon(Integer.parseInt(
                info.getProperty(Configuration.TX_DAEMON_SLEEPTIME_S, Configuration.TX_DAEMON_SLEEPTIME_S_DEFAULT)),
                this));
        txDaemon.setName("TxDaemon");
        txDaemon.setDaemon(true);
        txDaemon.start();
    }

    /**
     * Initialize all the  interfaces and datastructures
     * @throws MDBCServiceException
     */
    protected void initMusic() throws MDBCServiceException {
        this.musicInterface = MixinFactory.createMusicInterface(this, musicmixin, mdbcServerName, info);
        this.mdbcConnections = new HashMap<>();
    }
    
    protected void initSqlDatabase() throws MDBCServiceException {
        if(!this.sqlDBUrl.toLowerCase().startsWith("jdbc:postgresql")) {
            try {
                Connection sqlConnection = DriverManager.getConnection(this.sqlDBUrl, this.info);
                StringBuilder sql = new StringBuilder("CREATE DATABASE IF NOT EXISTS ")
                    .append(sqlDBName)
                    .append(";");
                Statement stmt = sqlConnection.createStatement();
                stmt.execute(sql.toString());
                sqlConnection.close();
            } catch (SQLException e) {
                logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.UNKNOWNERROR,
                    ErrorSeverity.CRITICAL,
                    ErrorTypes.GENERALSERVICEERROR);
                throw new MDBCServiceException(e.getMessage(), e);
            }
        }
        
        // Verify the tables in MUSIC match the tables in the database
        // and create triggers on any tables that need them
        try {
            MdbcConnection mdbcConn = (MdbcConnection) openConnection("init");
            mdbcConn.initDatabase();
            closeConnection("init");
        } catch (QueryException e) {
            logger.error("Error syncrhonizing tables");
            logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorTypes.QUERYERROR, ErrorSeverity.CRITICAL);
        }
    }
    
    /**
     * Get list of ranges to warmup from configuration file
     * if no configuration is provided, will return null
     * @return
     */
    private Set<Range> initWarmupRanges() {
        String warmupString = info.getProperty(Configuration.KEY_WARMUPRANGES);
        if (warmupString==null) {
            return null;
        }
        Set<Range> warmupRanges = new HashSet<>();
        String[] ranges = warmupString.split(",");
        for (String range: ranges) {
            warmupRanges.add(new Range(range.trim()));
        }
        return warmupRanges;
    }

    public MusicInterface getMusicInterface() {
    	return this.musicInterface;
    }
    
    public List<DatabasePartition> getPartitions() {
        return new ArrayList<>(connectionRanges.values());
	}

    /**
     * Get a list of ranges that are to be periodically warmed up
     * 
     * If no list is specified, all ranges except eventual consistency ranges are returned
     * @return
     */
	public Set<Range> getRangesToWarmup() {
        warmupLock.lock();
        Set<Range> returnSet;
        try {
            if(rangesToWarmup!=null) {
                returnSet = rangesToWarmup;
            }
            else {
                returnSet = getAllRanges();
                for (Range eventualRange: eventualRanges) {
                    returnSet.remove(eventualRange);
                }
            }
        }
        finally{
           warmupLock.unlock();
        }
        return returnSet;
    }

	/**
	 * Get a set of all ranges seen in the sql db
	 * @return
	 */
	private Set<Range> getAllRanges() {
	    DBInterface dbi = ((MdbcConnection) getConnection("daemon")).getDBInterface();
	    return dbi.getSQLRangeSet();
    }

    /**
	 * Get a list of ranges that are eventually consistent
	 * @return
	 */
    public Set<Range> getEventualRanges() {
        eventualLock.lock();
        Set<Range> returnSet;
        try {
            if(eventualRanges!=null){
                returnSet = new HashSet<>(eventualRanges);
            }
            else{
                returnSet= new HashSet<>();
            }
        }
        finally{
            eventualLock.unlock();
        }
        return returnSet;
    }

    public void setEventualRanges(Set<Range> eventualRanges) {
        eventualLock.lock();
        try {
            this.eventualRanges = eventualRanges;
        }
        finally{
            eventualLock.unlock();
        }
    }
    
    public String getMdbcServerName() {
        return mdbcServerName;
    }

    public void setMdbcServerName(String mdbcServerName) {
        this.mdbcServerName = mdbcServerName;
    }

    /**
     * Close connection and relinquish any locks held for that connection
     * @param connectionId
     */
    public void closeConnection(String connectionId){
        //\TODO check if there is a race condition
        if(mdbcConnections.containsKey(connectionId)) {
            transactionInfo.deleteTxProgress(connectionId);
            try {
                Connection conn = mdbcConnections.get(connectionId);
                if (conn!=null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.CRITICAL,
                        ErrorTypes.GENERALSERVICEERROR);
            }
            mdbcConnections.remove(connectionId);
        }
        
        connectionRanges.remove(connectionId);
        
    }

    /**
     * Opens a connection into database, setting up all necessary triggers, etc
     * @param id UUID of a connection
     */
	public Connection openConnection(String id) {
		Connection sqlConnection;
    	MdbcConnection newConnection;
        Utils.registerDefaultDrivers();
        //Create connection to local SQL DB

		try {
			sqlConnection = DriverManager.getConnection(this.sqlDBUrl+"/"+this.sqlDBName, this.info);
		} catch (SQLException e) {
		    logger.error("sql connection was not created correctly");
			logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL,
                    ErrorTypes.QUERYERROR);
			sqlConnection = null;
		}
		
		//TODO: later we could try to match it to some more sticky client id
        DatabasePartition ranges=new DatabasePartition(musicInterface.generateUniqueKey());
        connectionRanges.put(id,ranges);
        
        //Create MDBC connection
    	try {
			newConnection = new MdbcConnection(id,this.sqlDBUrl+"/"+this.sqlDBName, sqlConnection, info, this.musicInterface,
                transactionInfo,ranges, this);
		} catch (MDBCServiceException e) {
			logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.CRITICAL,
                    ErrorTypes.QUERYERROR);
			newConnection = null;
		}
		logger.info(EELFLoggerDelegate.applicationLogger,"Connection created for connection: "+id);

    	transactionInfo.createNewTransactionTracker(id, sqlConnection);
    	if(newConnection != null) {
            mdbcConnections.put(id,newConnection);
        }
    	return newConnection;
	}
    
    
    /**
     * This function returns the connection to the corresponding transaction 
     * @param id of the transaction, created using
     * @return
     */
    public Connection getConnection(String id) {
        if(mdbcConnections.containsKey(id)) {
            //\TODO: Verify if this make sense
            // Intent: reinitialize transaction progress, when it already completed the previous tx for the same connection
            if(transactionInfo.isComplete(id)) {
                transactionInfo.reinitializeTxProgress(id);
            }
            return mdbcConnections.get(id);
        }

        return openConnection(id);
    }
    
	public void initializeSystem() {
		//\TODO Prefetch data to system using the data ranges as guide 
		throw new UnsupportedOperationException("Function initialize system needs to be implemented id MdbcStateManager");
	}

	private void relinquish(DatabasePartition partition){
        try {
            musicInterface.relinquish(partition);
        } catch (MDBCServiceException e) {
            logger.error("Relinquish failed, would need to forcefully obtain lock later");
        }

    }

    public void setWarmupRanges(Set<Range> warmupRanges) {
        warmupLock.lock();
        try {
            this.rangesToWarmup = warmupRanges;
        }
        finally{
            warmupLock.unlock();
        }
    }
    
    public OwnershipAndCheckpoint getOwnAndCheck() {
        return ownAndCheck;
    }

    /**
     * Close all connections for this server, relinquishing any locks/partitions owned by this server
     */
    public void releaseAllPartitions() {
        for(String connection: this.mdbcConnections.keySet()) {
            closeConnection(connection);
        } 
    }
}