This commit is contained in:
zhanglianghy 2019-07-26 18:03:51 +08:00
commit 3291dd4992
37 changed files with 1869 additions and 489 deletions

27
Common/ulog_api.h Executable file
View File

@ -0,0 +1,27 @@
#ifndef _ULOG_API_H
#define _ULOG_API_H
#include <syslog.h>
#include "common_types.h"
#define MAX_MODULE_NAME_SZ 16
typedef struct _ulog {
char module_name[MAX_MODULE_NAME_SZ];
} ulog_t;
ulog_t *ulog_init(const char *module_name, u8 is_print);
void ulog_close(ulog_t *log);
void ulog_record(const ulog_t *log, int level, const char *fmt, ...);
#define ULOG_DEBUG(log, fmt, ...) ulog_record(log, LOG_DEBUG, fmt, ##__VA_ARGS__)
#define ULOG_INFO(log, fmt, ...) ulog_record(log, LOG_INFO, fmt, ##__VA_ARGS__)
#define ULOG_NOTICE(log, fmt, ...) ulog_record(log, LOG_NOTICE, fmt, ##__VA_ARGS__)
#define ULOG_WARNING(log, fmt, ...) ulog_record(log, LOG_WARNING, fmt, ##__VA_ARGS__)
#define ULOG_ERR(log, fmt, ...) ulog_record(log, LOG_ERR, fmt, ##__VA_ARGS__)
#define ULOG_CRIT(log, fmt, ...) ulog_record(log, LOG_CRIT, fmt, ##__VA_ARGS__)
#define ULOG_ALERT(log, fmt, ...) ulog_record(log, LOG_ALERT, fmt, ##__VA_ARGS__)
#define ULOG_EMERG(log, fmt, ...) ulog_record(log, LOG_EMERG, fmt, ##__VA_ARGS__)
#endif

View File

@ -25,11 +25,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define UTHASH_H
#define UTHASH_VERSION 2.1.0
#ifdef __KERNEL__
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/slab.h>
#else
#include <string.h> /* memcmp, memset, strlen */
#include <stddef.h> /* ptrdiff_t */
#include <stdlib.h> /* exit */
#endif
/* These macros use decltype or the earlier __typeof GNU extension.
As decltype is only available in newer compilers (VS2010 or gcc 4.3+
when compiling c++ source) this code uses whatever method is needed
@ -63,6 +67,7 @@ do {
#endif
/* a number of the hash function use uint32_t which isn't defined on Pre VS2010 */
#ifndef __KERNEL__
#if defined(_WIN32)
#if defined(_MSC_VER) && _MSC_VER >= 1600
#include <stdint.h>
@ -78,13 +83,23 @@ typedef unsigned char uint8_t;
typedef unsigned int uint32_t;
typedef unsigned char uint8_t;
#endif
#endif
#ifdef __KERNEL__
#ifndef uthash_malloc
#define uthash_malloc(sz) kmalloc(sz, GFP_KERNEL) /* malloc fcn */
#endif
#ifndef uthash_free
#define uthash_free(ptr,sz) kfree(ptr) /* free fcn */
#endif
#else
#ifndef uthash_malloc
#define uthash_malloc(sz) malloc(sz) /* malloc fcn */
#endif
#ifndef uthash_free
#define uthash_free(ptr,sz) free(ptr) /* free fcn */
#endif
#endif
#ifndef uthash_bzero
#define uthash_bzero(a,n) memset(a,'\0',n)
#endif
@ -128,8 +143,12 @@ typedef unsigned char uint8_t;
/* malloc failures result in lost memory, hash tables are unusable */
#ifndef uthash_fatal
#ifdef __KERNEL__
#define uthash_fatal(msg) BUG() /* fatal OOM error */
#else
#define uthash_fatal(msg) exit(-1) /* fatal OOM error */
#endif
#endif
#define HASH_RECORD_OOM(oomed) uthash_fatal("out of memory")
#define IF_HASH_NONFATAL_OOM(x)

View File

@ -143,28 +143,6 @@ abstract class AbstractStore<T> {
return result;
}
/**
* Lists the stored items returned by the given statement.
*
* @param ps The statement (which must be ready for execution). It is the caller's responsibility to close this.
*
* @return The stored items.
*
* @throws StoreException if an error occurs.
*/
protected List<T> listFromStatement(PreparedStatement ps) throws StoreException {
List<T> result = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(fromResultSet(rs));
}
} catch (SQLException e) {
LOG.error("Error listing matching items from {}", tableName, e);
throw new StoreException(e);
}
return result;
}
/**
* Extracts the first item returned by the given statement, if any.
*
@ -187,6 +165,28 @@ abstract class AbstractStore<T> {
}
}
/**
* Lists the stored items returned by the given statement.
*
* @param ps The statement (which must be ready for execution). It is the caller's responsibility to close this.
*
* @return The stored items.
*
* @throws StoreException if an error occurs.
*/
protected List<T> listFromStatement(PreparedStatement ps) throws StoreException {
List<T> result = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(fromResultSet(rs));
}
} catch (SQLException e) {
LOG.error("Error listing matching items from {}", tableName, e);
throw new StoreException(e);
}
return result;
}
/**
* Converts a single row in a result set to an instance of the managed type.
*

View File

@ -79,11 +79,7 @@ public class DomainHandler {
try {
domains = iidMStore.getDomains();
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domains");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e, "Internal error getting domains");
}
return Response.ok(domains).build();
}
@ -104,11 +100,7 @@ public class DomainHandler {
try {
domain = iidMStore.readDomain(domainId);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting domain");
}
if (domain == null) {
@ -157,11 +149,7 @@ public class DomainHandler {
}
domain = iidMStore.writeDomain(domain);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error creating domain");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error creating domain");
}
return Response.status(201).entity(domain).build();
}
@ -194,11 +182,7 @@ public class DomainHandler {
claimCache.clear();
return Response.status(200).entity(domain).build();
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error putting domain");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error putting domain");
}
}
@ -224,11 +208,7 @@ public class DomainHandler {
return Response.status(404).entity(idmerror).build();
}
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error deleting Domain");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error deleting Domain");
}
claimCache.clear();
return Response.status(204).build();
@ -268,19 +248,15 @@ public class DomainHandler {
}
Domain domain = null;
User user;
Role role;
String roleId;
User user = null;
Role role = null;
String roleId = null;
// validate domain id
try {
domain = iidMStore.readDomain(domainId);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting domain");
}
if (domain == null) {
IDMError idmerror = new IDMError();
@ -292,11 +268,7 @@ public class DomainHandler {
try {
user = iidMStore.readUser(userId);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting user");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting user");
}
if (user == null) {
IDMError idmerror = new IDMError();
@ -317,11 +289,7 @@ public class DomainHandler {
try {
role = iidMStore.readRole(roleId);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting role");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting role");
}
if (role == null) {
IDMError idmerror = new IDMError();
@ -338,22 +306,14 @@ public class DomainHandler {
return Response.status(403).entity(idmerror).build();
}
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error creating grant");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error creating grant");
}
// create grant
try {
grant = iidMStore.writeGrant(grant);
} catch (IDMStoreException e) {
LOG.error("StoreException: ", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error creating grant");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error creating grant");
}
claimCache.clear();
@ -384,11 +344,7 @@ public class DomainHandler {
try {
domain = iidMStore.readDomain(domainId);
} catch (IDMStoreException se) {
LOG.error("StoreException: ", se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(se,"Internal error getting domain");
}
if (domain == null) {
IDMError idmerror = new IDMError();
@ -437,19 +393,11 @@ public class DomainHandler {
roleList.add(role);
}
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting Roles");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e, "Internal error getting Roles");
}
claim.setRoles(roleList);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting user");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting user");
}
return Response.ok(claim).build();
@ -479,11 +427,7 @@ public class DomainHandler {
try {
domain = iidMStore.readDomain(domainId);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting domain");
}
if (domain == null) {
IDMError idmerror = new IDMError();
@ -494,11 +438,7 @@ public class DomainHandler {
try {
user = iidMStore.readUser(userId);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting user");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting user");
}
if (user == null) {
IDMError idmerror = new IDMError();
@ -513,17 +453,21 @@ public class DomainHandler {
roleList.add(role);
}
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting Roles");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting Roles");
}
Roles roles = new Roles();
roles.setRoles(roleList);
return Response.ok(roles).build();
}
private Response getResponse500(IDMStoreException e, String msg) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage(msg);
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
}
/**
* Delete a grant.
*
@ -548,11 +492,7 @@ public class DomainHandler {
try {
domain = iidMStore.readDomain(domainId);
} catch (IDMStoreException e) {
LOG.error("Error deleting Grant", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting domain");
}
if (domain == null) {
IDMError idmerror = new IDMError();
@ -563,11 +503,7 @@ public class DomainHandler {
try {
user = iidMStore.readUser(userId);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting user");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting user");
}
if (user == null) {
IDMError idmerror = new IDMError();
@ -578,11 +514,7 @@ public class DomainHandler {
try {
role = iidMStore.readRole(roleId);
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting Role");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error getting Role");
}
if (role == null) {
IDMError idmerror = new IDMError();
@ -600,11 +532,7 @@ public class DomainHandler {
}
iidMStore.deleteGrant(existingGrant.getGrantid());
} catch (IDMStoreException e) {
LOG.error("StoreException", e);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error creating grant");
idmerror.setDetails(e.getMessage());
return Response.status(500).entity(idmerror).build();
return getResponse500(e,"Internal error creating grant");
}
claimCache.clear();
return Response.status(204).build();

View File

@ -11,10 +11,18 @@
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license.
*/
package org.opendaylight.aaa.shiro.idm;
import java.util.Collection;
import java.util.Objects;
import org.opendaylight.aaa.api.ClaimCache;
import org.opendaylight.aaa.api.IDMStoreException;
import org.opendaylight.aaa.api.IIDMStore;
import org.opendaylight.aaa.api.model.IDMError;
import org.opendaylight.aaa.api.model.User;
import org.opendaylight.aaa.api.model.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
@ -26,14 +34,8 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.opendaylight.aaa.api.ClaimCache;
import org.opendaylight.aaa.api.IDMStoreException;
import org.opendaylight.aaa.api.IIDMStore;
import org.opendaylight.aaa.api.model.IDMError;
import org.opendaylight.aaa.api.model.User;
import org.opendaylight.aaa.api.model.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Objects;
/**
* @author Dong Xiancun
@ -49,7 +51,7 @@ import org.slf4j.LoggerFactory;
public class UserHandler {
private static final Logger LOG = LoggerFactory.getLogger(UserHandler.class);
private static final String PW_PATTERN = "/^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{8,}$/";
private static final String PW_PATTERN = "^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{8,}$";
/**
* If a user is created through the <code>/auth/v1/users</code> rest
* endpoint without a password, the default password is assigned to the
@ -120,8 +122,7 @@ public class UserHandler {
* Extracts the user represented by <code>id</code>. The password and salt
* fields are redacted for security reasons.
*
* @param id
* the unique id of representing the user account
* @param id the unique id of representing the user account
* @return A response with the user information, or internal error if one
* occurs
*/
@ -161,10 +162,8 @@ public class UserHandler {
* If a password is not provided, please ensure you change the default
* password ASAP for security reasons!
*
* @param info
* passed from Jersey
* @param user
* the user defined in the JSON payload
* @param info passed from Jersey
* @param user the user defined in the JSON payload
* @return A response stating success or failure of user creation
*/
@POST
@ -237,7 +236,6 @@ public class UserHandler {
if (response.getStatus() != 200) {
return response;
}
try {
// At this point, fields have been properly verified. Create the
// user account
@ -270,15 +268,13 @@ public class UserHandler {
private Response providePasswordError(String s) {
return new IDMError(407, s).response();
}
/**
* REST endpoint to update a user account.
*
* @param info
* passed from Jersey
* @param user
* the user defined in the JSON payload
* @param id
* the unique id for the user that will be updated
* @param info passed from Jersey
* @param user the user defined in the JSON payload
* @param id the unique id for the user that will be updated
* @return A response stating success or failure of the user update
*/
@PUT
@ -330,10 +326,8 @@ public class UserHandler {
/**
* REST endpoint to delete a user account.
*
* @param info
* passed from Jersey
* @param id
* the unique id of the user which is being deleted
* @param info passed from Jersey
* @param id the unique id of the user which is being deleted
* @return A response stating success or failure of user deletion
*/
@DELETE
@ -360,10 +354,8 @@ public class UserHandler {
/**
* Creates a <code>Response</code> related to an internal server error.
*
* @param verbal
* such as "creating", "deleting", "updating"
* @param ex
* The exception, which is logged locally
* @param verbal such as "creating", "deleting", "updating"
* @param ex The exception, which is logged locally
* @return A response containing internal error with specific reasoning
*/
private Response internalError(final String verbal, final Exception ex) {
@ -376,8 +368,7 @@ public class UserHandler {
* Creates a <code>Response</code> related to the user not providing a
* required field.
*
* @param fieldName
* the name of the field which is missing
* @param fieldName the name of the field which is missing
* @return A response explaining that the request is missing a field
*/
private Response missingRequiredField(final String fieldName) {
@ -392,10 +383,8 @@ public class UserHandler {
* Creates a <code>Response</code> related to the user providing a field
* that is too long.
*
* @param fieldName
* the name of the field that is too long
* @param maxFieldLength
* the maximum length of <code>fieldName</code>
* @param fieldName the name of the field that is too long
* @param maxFieldLength the maximum length of <code>fieldName</code>
* @return A response containing the bad field and the maximum field length
*/
private Response providedFieldTooLong(final String fieldName, final int maxFieldLength) {
@ -406,10 +395,8 @@ public class UserHandler {
* Creates the client-facing message related to the user providing a field
* that is too long.
*
* @param fieldName
* the name of the field that is too long
* @param maxFieldLength
* the maximum length of <code>fieldName</code>
* @param fieldName the name of the field that is too long
* @param maxFieldLength the maximum length of <code>fieldName</code>
* @return a response containing the too long field and its length
*/
private static String getProvidedFieldTooLongMessage(final String fieldName, final int maxFieldLength) {
@ -422,8 +409,7 @@ public class UserHandler {
* Prepares a user account for output by redacting the appropriate fields.
* This method side-effects the <code>user</code> parameter.
*
* @param user
* the user account which will have fields redacted
* @param user the user account which will have fields redacted
*/
private static void redactUserPasswordInfo(final User user) {
user.setPassword(REDACTED_PASSWORD);
@ -433,8 +419,7 @@ public class UserHandler {
/**
* Validate the input field length.
*
* @param inputField
* the field to check
* @param inputField the field to check
* @return true if input field bigger than the MAX_FIELD_LEN
*/
private boolean checkInputFieldLength(final String inputField) {

View File

@ -14,25 +14,19 @@
package org.opendaylight.aaa.datastore.h2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.aaa.api.model.Domain;
import org.opendaylight.aaa.api.model.Domains;
import java.sql.*;
import java.util.Objects;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Dong Xiancun
*
@ -71,23 +65,45 @@ public class DomainStoreTest {
}
@Test
public void deleteDomainsTest() throws SQLException, Exception {
public void deleteDomainsTest() throws Exception {
IdmLightSimpleConnectionProvider dbConnectionFactory = new IdmLightSimpleConnectionProvider(
new IdmLightConfigBuilder().dbUser("foo").dbPwd("bar").build());
DomainStore ds = new DomainStore(dbConnectionFactory);
String domainId = "Testing12345";
notNullDomain(ds);
assertNotNull(ds.getDomains(domainId));
assertEquals(ds.getDomain(domainId).getDomainid(), domainId);
assertNull(ds.deleteDomain("11111111111111111"));
ds.deleteDomain(domainId);
assertNull(ds.getDomain(domainId));
}
// Run Test
Domain testDomain = new Domain();
@Test
public void putDomainsTest() throws StoreException {
DomainStore ds = new DomainStore(
new IdmLightSimpleConnectionProvider(new IdmLightConfigBuilder().dbUser("foo").dbPwd("bar").build()));
assertNotNull(ds.getTableCreationStatement());
Domain testDomain = notNullDomain(ds);
testDomain.setName("newName");
testDomain.setEnabled(Boolean.FALSE);
Domain res = ds.putDomain(testDomain);
testDomain.setDescription("test domain ,so used with disable");
assertNotNull(res);
assertEquals("newName",res.getName());
assertFalse(res.isEnabled());
}
private Domain notNullDomain(DomainStore ds)throws StoreException {
String domainId = "Testing12345";
Domain testDomain = ds.getDomain(domainId);
if(Objects.isNull(testDomain)){
testDomain = new Domain();
testDomain.setDomainid(domainId);
testDomain.setName(domainId);
testDomain.setEnabled(Boolean.TRUE);
DomainStore ds = new DomainStore(
new IdmLightSimpleConnectionProvider(new IdmLightConfigBuilder().dbUser("foo").dbPwd("bar").build()));
ds.createDomain(testDomain);
assertNotNull(ds.getDomains(domainId));
assertEquals(ds.getDomain(domainId).getDomainid(), domainId);
ds.deleteDomain(domainId);
assertNull(ds.getDomain(domainId));
}
return testDomain;
}
public ResultSet getMockedResultSet() throws SQLException {
@ -108,4 +124,6 @@ public class DomainStoreTest {
*
* -------------------------------------------------------------------------
* 2019/7/3 Dong Xiancun creat
* -------------------------------------------------------------------------
* 2019/7/23 Ma Xiaonan modify
*/

View File

@ -14,14 +14,8 @@
package org.opendaylight.aaa.datastore.h2;
import java.io.File;
import java.sql.SQLException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.*;
import org.opendaylight.aaa.api.IDMStoreException;
import org.opendaylight.aaa.api.IDMStoreUtil;
import org.opendaylight.aaa.api.IIDMStore;
import org.opendaylight.aaa.api.model.Domain;
@ -31,15 +25,23 @@ import org.opendaylight.aaa.api.model.User;
import org.opendaylight.aaa.api.password.service.PasswordHashService;
import org.opendaylight.aaa.impl.password.service.DefaultPasswordHashService;
import java.io.File;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.*;
public class H2StoreTest {
private static String PATHNAME1 = "./data" + File.separatorChar + "idmlight.db.mv.db";
private static String PATHNAME2 = "./data" + File.separatorChar + "idmlight.db.trace.db";
@BeforeClass
public static void start() {
File file = new File("idmlight.db.mv.db");
File file = new File(PATHNAME1);
if (file.exists()) {
file.delete();
}
file = new File("idmlight.db.trace.db");
file = new File(PATHNAME2);
if (file.exists()) {
file.delete();
}
@ -47,11 +49,11 @@ public class H2StoreTest {
@AfterClass
public static void end() {
File file = new File("idmlight.db.mv.db");
File file = new File(PATHNAME1);
if (file.exists()) {
file.delete();
}
file = new File("idmlight.db.trace.db");
file = new File(PATHNAME2);
if (file.exists()) {
file.delete();
}
@ -61,7 +63,7 @@ public class H2StoreTest {
private PasswordHashService passwordService = new DefaultPasswordHashService();
@Before
public void before() throws StoreException, SQLException {
public void before() throws StoreException {
IdmLightSimpleConnectionProvider dbConnectionFactory = new IdmLightSimpleConnectionProvider(
new IdmLightConfigBuilder().dbUser("foo").dbPwd("bar").build());
UserStore us = new UserStore(dbConnectionFactory, passwordService);
@ -80,20 +82,207 @@ public class H2StoreTest {
public void testCreateDefaultDomain() throws StoreException {
Domain domain = new Domain();
Assert.assertEquals(true, domain != null);
DomainStore ds = new DomainStore(
new IdmLightSimpleConnectionProvider(new IdmLightConfigBuilder().dbUser("foo").dbPwd("bar").build()));
IdmLightSimpleConnectionProvider dbConnectionFactory = new IdmLightSimpleConnectionProvider(
new IdmLightConfigBuilder().dbUser("foo").dbPwd("bar").build());
DomainStore ds = new DomainStore(dbConnectionFactory);
domain.setName(IIDMStore.DEFAULT_DOMAIN);
domain.setEnabled(true);
domain = ds.createDomain(domain);
Assert.assertEquals(true, domain != null);
}
@Test
public void testUser() throws StoreException, IDMStoreException {
User user = h2Store.createUser("test2",
"Cmcc@10086",
IIDMStore.DEFAULT_DOMAIN,
"user test2",
"test2@cmcc.com",true,"45fv12dU");
assertNotNull(user);
assertNotNull(h2Store.readUser(user.getUserid()));
user.setEnabled(false);
assertNotNull(h2Store.updateUser(user));
try{
user.setEmail(getExpectName());
h2Store.updateUser(user);
fail("update user error");
}catch (IDMStoreException e){
assertThat(e.getMessage(),containsString("SQL Exception"));
}
assertFalse(h2Store.readUser(user.getUserid()).isEnabled());
assertNotNull(h2Store.deleteUser(user.getUserid()));
}
private String getExpectName() {
return "1221r13r1rfdfsafsdfadfadfasfadsfdsfdaf" +
"dsfdsfafsdfadfasfsafdsafdfaadfdaffgdsfa" +
"safdsafafsafdasgfdsafdsafagadfadsfdsfdafda" +
"adfasdfdsafadsfsag4ef2313414r314313143113431" +
"1431413241231543143143154354321r3243fdsf3rfdr32f";
}
@Test
public void writeUserTest() throws IDMStoreException {
User user = mockUser("test3");
h2Store.writeUser(user);
try{
h2Store.writeUser(user);
fail("get IDM store exception");
}catch (IDMStoreException e){
assertThat(e.getMessage(),containsString("SQL Exception"));
h2Store.deleteUser(user.getUserid());
}
try{
h2Store.updateUser(mockUser("test4"));
}catch (IDMStoreException ex){
assertThat(ex.getMessage(),containsString("SQL Exception"));
}
}
@Test
public void testRole() throws IDMStoreException {
Role role = mockRole("testRole");
assertNotNull(role);
h2Store.writeRole(role);
try{
h2Store.writeRole(role);
fail("get IDM store exception");
}catch (IDMStoreException e){
assertThat(e.getMessage(),containsString("SQL Exception"));
}
role.setName("changeRole");
assertNotNull(h2Store.updateRole(role));
try{
role.setDescription(getExpectName());
h2Store.updateRole(role);
fail("update role error");
}catch (IDMStoreException e){
assertThat(e.getMessage(),containsString("SQL Exception"));
}
assertNotNull(h2Store.readRole(role.getRoleid()));
assertNotNull(h2Store.deleteRole(role.getRoleid()));
}
private Role mockRole(String id) {
Role role = new Role();
role.setRoleid(id);
role.setDomainid(IIDMStore.DEFAULT_DOMAIN);
role.setName(id);
role.setDescription("test role");
return role;
}
@Test
public void testDomain() throws IDMStoreException {
Domain domain = mockDomain("cmcc");
assertNotNull(domain);
h2Store.writeDomain(domain);
try{
h2Store.writeDomain(domain);
fail("get IDM store exception");
}catch (IDMStoreException e){
assertThat(e.getMessage(),containsString("Error creating domain"));
}
domain.setName("changeDomain");
assertNotNull(h2Store.updateDomain(domain));
try{
domain.setName(getExpectName());
h2Store.updateDomain(domain);
fail("update domain error");
}catch (IDMStoreException e){
assertThat(e.getMessage(),containsString("Error updating domain"));
}
assertNotNull(h2Store.readDomain(domain.getDomainid()));
assertNotNull(h2Store.deleteDomain(domain.getDomainid()));
}
private Domain mockDomain(String id) {
Domain domain = new Domain();
domain.setDomainid(id);
domain.setName("testDomain");
domain.setEnabled(true);
domain.setDescription("test domain");
return domain;
}
@Test
public void testGrants() throws IDMStoreException {
Grant grant = mockGrants("testRole");
assertNotNull(grant);
h2Store.writeGrant(grant);
try{
h2Store.writeGrant(grant);
fail("get IDM store exception");
}catch (IDMStoreException e){
assertThat(e.getMessage(),containsString("SQL Exception"));
}
assertNotNull(h2Store.readGrant(IIDMStore.DEFAULT_DOMAIN,grant.getUserid(),grant.getRoleid()));
assertNotNull(h2Store.readGrant(grant.getGrantid()));
assertNotNull(h2Store.deleteGrant(grant.getGrantid()));
}
private Grant mockGrants(String id) {
Grant grant = new Grant();
grant.setRoleid("testRole");
grant.setDomainid(IIDMStore.DEFAULT_DOMAIN);
grant.setGrantid(id);
grant.setUserid("test");
return grant;
}
private User mockUser(String name) {
User user = new User();
user.setEnabled(true);
user.setName(name);
user.setDomainid(IIDMStore.DEFAULT_DOMAIN);
user.setPassword("Cmcc@10086");
user.setEmail("test2@cmcc.com");
user.setSalt("45fv12dU");
user.setDescription("user test");
return user;
}
@Test
public void testCreateTempRole() throws StoreException {
Role role = h2Store.createRole("temp", "temp domain", "Temp Testing role");
Assert.assertEquals(true, role != null);
}
@Test
public void testGetAllValues(){
try {
assertNotNull(h2Store.getDomains());
} catch (IDMStoreException e) {
assertThat(e.getMessage(),containsString("SQL Exception"));
}
try {
assertNotNull(h2Store.getUsers());
} catch (IDMStoreException e) {
assertThat(e.getMessage(),containsString("SQL Exception"));
}
try {
assertNotNull(h2Store.getUsers("testUser",IIDMStore.DEFAULT_DOMAIN));
} catch (IDMStoreException e) {
assertThat(e.getMessage(),containsString("SQL Exception"));
}
try {
assertTrue(h2Store.getGrants("111").getGrants().isEmpty());
} catch (IDMStoreException e) {
assertThat(e.getMessage(),containsString("SQL Exception"));
}
try {
assertNotNull(h2Store.getGrants(IIDMStore.DEFAULT_DOMAIN,"testUser"));
} catch (IDMStoreException e) {
assertThat(e.getMessage(),containsString("SQL Exception"));
}
try {
assertNotNull(h2Store.getRoles());
} catch (IDMStoreException e) {
assertThat(e.getMessage(),containsString("SQL Exception"));
}
}
@Test
public void testCreateUser() throws StoreException {
User user = h2Store.createUser("test", "pass", "domain", "desc",
@ -209,10 +398,12 @@ public class H2StoreTest {
}
/**
* Revision history
*
* <p>
* -------------------------------------------------------------------------
* Date Author Note
*
* <p>
* -------------------------------------------------------------------------
* 2019/7/3 Dong Xiancun creat
* -------------------------------------------------------------------------
* 2019/7/ Dong Xiancun creat
*/

View File

@ -14,6 +14,9 @@
package org.opendaylight.aaa.datastore.h2;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import java.io.File;
@ -33,6 +36,7 @@ public class IdmLightConfigTest {
.isEqualTo("jdbc:h2:./data" + File.separatorChar + "idmlight.db");
assertThat(config.getDbUser()).isEqualTo("foo");
assertThat(config.getDbPwd()).isEqualTo("bar");
config.log();
assertThat(config.getDbValidTimeOut()).isEqualTo(3);
}
@ -55,6 +59,42 @@ public class IdmLightConfigTest {
assertThat(config.getDbConnectionString()).isEqualTo("jdbc:mysql://localhost/test");
}
@Test
public void testIdmBuilder() {
IdmLightConfigBuilder builder = new IdmLightConfigBuilder().dbUser("foo").dbPwd("bar");
builder.dbName("idmlight.db");
builder.dbDriver("org.h2.Driver");
builder.dbValidTimeOut(3);
builder.dbConnectionStringPrefix("jdbc:h2:");
IdmLightConfig config = builder.build();
IdmLightConfig config2 = builder.build();
assertNotNull(config.toString());
assertEquals(config.hashCode(),checkHashCode(config));
assertEquals(config, config2);
assertThat(config.getDbConnectionString())
.isEqualTo("jdbc:h2:./data" + File.separatorChar + "idmlight.db");
assertThat(config.getDbDriver())
.isEqualTo("org.h2.Driver");
assertThat(config.getDbValidTimeOut()).isEqualTo(3);
assertThat(config.getDbConnectionStringPrefix()).isEqualTo("jdbc:h2:");
}
private int checkHashCode(IdmLightConfig config) {
int h = 5381;
h += (h << 5) + config.getDbName().hashCode();
h += (h << 5) + config.getDbDirectory().hashCode();
h += (h << 5) + config.getDbDriver().hashCode();
h += (h << 5) + config.getDbUser().hashCode();
h += (h << 5) + config.getDbPwd().hashCode();
h += (h << 5) + config.getDbValidTimeOut();
h += (h << 5) + config.getDbConnectionStringPrefix().hashCode();
h += (h << 5) + config.getDbConnectionString().hashCode();
return h;
}
}
/**
* Revision history
@ -64,4 +104,6 @@ public class IdmLightConfigTest {
*
* -------------------------------------------------------------------------
* 2019/7/3 Dong Xiancun creat
* -------------------------------------------------------------------------
* 2019/7/23 Ma Xiaonan modify
*/

View File

@ -14,20 +14,17 @@
package org.opendaylight.aaa.datastore.h2;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.aaa.api.model.Roles;
import java.sql.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.aaa.api.model.Roles;
public class RoleStoreTest {
private final Connection connectionMock = mock(Connection.class);

View File

@ -14,19 +14,21 @@
package org.opendaylight.aaa.datastore.h2;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.aaa.api.model.Users;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.aaa.api.model.Users;
import org.opendaylight.aaa.impl.password.service.DefaultPasswordHashService;
public class UserStoreTest {
@ -72,6 +74,7 @@ public class UserStoreTest {
Mockito.when(rsMock.getString(UserStore.SQL_PASSWORD)).thenReturn("Pswd_1");
Mockito.when(rsMock.getString(UserStore.SQL_DESCR)).thenReturn("Desc_1");
Mockito.when(rsMock.getInt(UserStore.SQL_ENABLED)).thenReturn(1);
Mockito.when(rsMock.getString(UserStore.SQL_DOMAIN_ID)).thenReturn("domainid");
return rsMock;
}
}

View File

@ -74,7 +74,9 @@ public class PasswordHashTest {
role.setName("admin");
Mockito.when(store.readRole("admin")).thenReturn(role);
Mockito.when(store.getUsers(creds.username(), creds.domain())).thenReturn(users);
Mockito.when(store.getUsers()).thenReturn(users);
Mockito.when(store.getGrants(creds.domain(), creds.username())).thenReturn(grants);
Mockito.when(store.getGrants(grant.getUserid())).thenReturn(grants);
}
@Test
@ -99,6 +101,18 @@ public class PasswordHashTest {
return "sdn";
}
}
@Test
public void testOthers() {
IdmLightProxy proxy = new IdmLightProxy(store, passwordService);
proxy.listDomains("admin");
proxy.listRoles("admin","sdn");
try {
proxy.listUserIDs();
} catch (IDMStoreException e) {
e.printStackTrace();
}
}
}
/**
* Revision history

View File

@ -28,6 +28,7 @@ import org.opendaylight.aaa.api.model.Domain;
import org.opendaylight.aaa.api.model.Domains;
import org.opendaylight.aaa.api.model.IDMError;
import org.opendaylight.aaa.api.model.Roles;
import org.opendaylight.aaa.shiro.idm.DomainHandler;
public class DomainHandlerTest extends HandlerTest {
@ -37,12 +38,12 @@ public class DomainHandlerTest extends HandlerTest {
Domains domains = target("/v1/domains").request().get(Domains.class);
assertNotNull(domains);
assertEquals(1, domains.getDomains().size());
assertTrue(domains.getDomains().get(0).getName().equals("sdn"));
assertEquals("sdn", domains.getDomains().get(0).getName());
// check existing domain
Domain domain = target("/v1/domains/0").request().get(Domain.class);
assertNotNull(domain);
assertTrue(domain.getName().equals("sdn"));
assertEquals("sdn", domain.getName());
// check not exist domain
try {
@ -54,19 +55,28 @@ public class DomainHandlerTest extends HandlerTest {
// check create domain
Map<String, String> domainData = new HashMap<>();
Response clientResponse = target("/v1/domains").request().post(entity(domainData));
assertEquals(201, clientResponse.getStatus());
domainData.put("name", "dom1");
domainData.put("description", "test dom");
domainData.put("enabled", "true");
Response clientResponse = target("/v1/domains").request().post(entity(domainData));
clientResponse = target("/v1/domains").request().post(entity(domainData));
assertEquals(201, clientResponse.getStatus());
// check update domain data
domainData.put("name", "dom1Update");
clientResponse = target("/v1/domains/1").request().put(entity(domainData));
assertEquals(200, clientResponse.getStatus());
clientResponse = target("/v1/domains/101").request().put(entity(domainData));
assertEquals(404, clientResponse.getStatus());
domain = target("/v1/domains/1").request().get(Domain.class);
assertNotNull(domain);
assertTrue(domain.getName().equals("dom1Update"));
assertEquals("dom1Update", domain.getName());
// check create grant
Map<String, String> grantData = new HashMap<>();
@ -74,6 +84,18 @@ public class DomainHandlerTest extends HandlerTest {
clientResponse = target("/v1/domains/1/users/0/roles").request().post(entity(grantData));
assertEquals(201, clientResponse.getStatus());
clientResponse = target("/v1/domains/1/users/100/roles").request().post(entity(grantData));
assertEquals(404, clientResponse.getStatus());
grantData.put("roleid", "10ywre");
clientResponse = target("/v1/domains/1/users/0/roles").request().post(entity(grantData));
assertEquals(404, clientResponse.getStatus());
grantData.put("roleid", "52");
clientResponse = target("/v1/domains/1/users/0/roles").request().post(entity(grantData));
assertEquals(404, clientResponse.getStatus());
grantData.put("roleid", "1");
// check create existing grant
clientResponse = target("/v1/domains/1/users/0/roles").request().post(entity(grantData));
assertEquals(403, clientResponse.getStatus());
@ -82,6 +104,13 @@ public class DomainHandlerTest extends HandlerTest {
clientResponse = target("/v1/domains/5/users/0/roles").request().post(entity(grantData));
assertEquals(404, clientResponse.getStatus());
// //异常测试
// // check create grant
// Map<String, String> grantData2 = new HashMap<>();
// grantData2.put("roleid", "2");
// clientResponse = target("/v1/domains/(select teId from teacher where teName='Rona')/users/0/roles").request().post(entity(grantData));
// assertEquals(500, clientResponse.getStatus());
// check validate user (admin)
Map<String, String> usrPwdData = new HashMap<>();
usrPwdData.put("username", "admin");
@ -89,6 +118,28 @@ public class DomainHandlerTest extends HandlerTest {
clientResponse = target("/v1/domains/0/users/roles").request().post(entity(usrPwdData));
assertEquals(200, clientResponse.getStatus());
//check domain is null
clientResponse = target("/v1/domains/12/users/roles").request().post(entity(usrPwdData));
assertEquals(404, clientResponse.getStatus());
//check user pwd with null parameter
//check domain is null
usrPwdData.remove("username");
clientResponse = target("/v1/domains/0/users/roles").request().post(entity(usrPwdData));
assertEquals(400, clientResponse.getStatus());
usrPwdData.put("username", "admin");
usrPwdData.remove("userpwd");
clientResponse = target("/v1/domains/0/users/roles").request().post(entity(usrPwdData));
assertEquals(400, clientResponse.getStatus());
usrPwdData.put("userpwd", "admin");
//check user is null
usrPwdData.put("username","12321421");
clientResponse = target("/v1/domains/0/users/roles").request().post(entity(usrPwdData));
assertEquals(404, clientResponse.getStatus());
usrPwdData.put("username", "admin");
// check validate user (admin) with wrong password
usrPwdData.put("userpwd", "1234");
clientResponse = target("/v1/domains/0/users/roles").request().post(entity(usrPwdData));
@ -107,6 +158,12 @@ public class DomainHandlerTest extends HandlerTest {
// expected
}
try {
target("/v1/domains/19/users/0/roles").request().get(IDMError.class);
fail("Should fail with 404!");
} catch (NotFoundException e) {
// expected
}
// check delete grant
clientResponse = target("/v1/domains/0/users/0/roles/0").request().delete();
assertEquals(204, clientResponse.getStatus());
@ -115,6 +172,16 @@ public class DomainHandlerTest extends HandlerTest {
clientResponse = target("/v1/domains/3/users/0/roles/0").request().delete();
assertEquals(404, clientResponse.getStatus());
// check delete grant for invalid user
clientResponse = target("/v1/domains/0/users/15/roles/0").request().delete();
assertEquals(404, clientResponse.getStatus());
// check delete grant for invalid role
clientResponse = target("/v1/domains/0/users/0/roles/134").request().delete();
assertEquals(404, clientResponse.getStatus());
// check delete domain
clientResponse = target("/v1/domains/1").request().delete();
assertEquals(204, clientResponse.getStatus());
@ -143,6 +210,7 @@ public class DomainHandlerTest extends HandlerTest {
clientResponse = target("/v1/domains/1/users/0/roles").request().post(entity(grantData));
assertEquals(400, clientResponse.getStatus());
}
}
/**
* Revision history

View File

@ -69,9 +69,32 @@ public class RoleHandlerTest extends HandlerTest {
try {
clientResponse = target("/v1/roles").request().post(entity(roleData));
assertEquals(404, clientResponse.getStatus());
roleData.put("name", getMaxLengthName());
target("/v1/roles").request().post(entity(roleData));
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
roleData.put("name", "role1");
//POST ERROR
roleData.remove("domainid");
try {
clientResponse = target("/v1/roles").request().post(entity(roleData));
assertEquals(404, clientResponse.getStatus());
roleData.put("domainid", getMaxLengthName());
target("/v1/roles").request().post(entity(roleData));
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
roleData.put("domainid", "0");
roleData.remove("description");
try {
target("/v1/roles").request().post(entity(roleData));
roleData.put("description", getMaxLengthName());
target("/v1/roles").request().post(entity(roleData));
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
roleData.put("description", "test Role");
// check update Role data
roleData.put("name", "role1Update");
@ -81,6 +104,25 @@ public class RoleHandlerTest extends HandlerTest {
assertNotNull(role);
assertTrue(role.getName().equals("role1Update"));
//PUT Error
roleData.put("name", getMaxLengthName());
clientResponse = target("/v1/roles/2").request().put(entity(roleData));
assertEquals(400, clientResponse.getStatus());
roleData.put("name", "role1Update");
roleData.put("description", getMaxLengthName());
clientResponse = target("/v1/roles/2").request().put(entity(roleData));
assertEquals(400, clientResponse.getStatus());
roleData.put("description", "test Role");
HashMap<String,String> newRole = new HashMap<>();
newRole.put("name", "role1Update");
newRole.put("domainid", "0");
newRole.put("description", "test Role");
clientResponse = target("/v1/roles/111111").request().put(entity(newRole));
assertEquals(404, clientResponse.getStatus());
// check delete Role
clientResponse = target("/v1/roles/2").request().delete();
assertEquals(204, clientResponse.getStatus());
@ -102,6 +144,16 @@ public class RoleHandlerTest extends HandlerTest {
clientResponse = target("/v1/roles").request().post(entity(roleData));
assertEquals(400, clientResponse.getStatus());
}
private String getMaxLengthName() {
return "abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn";
}
}
/**
* Revision history

View File

@ -14,24 +14,23 @@
package org.opendaylight.aaa.shiro.idm.rest.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.aaa.api.model.IDMError;
import org.opendaylight.aaa.api.model.User;
import org.opendaylight.aaa.api.model.Users;
@Ignore
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class UserHandlerTest extends HandlerTest {
@Test
@ -59,14 +58,16 @@ public class UserHandlerTest extends HandlerTest {
}
// check create user
Map<String, String> usrData = new HashMap<>();
Map<String, Object> usrData = new HashMap<>();
usrData.put("name", "usr1");
usrData.put("description", "test user");
usrData.put("enabled", "true");
// usrData.put("description", "test user");
// usrData.put("enabled", "true");
usrData.put("email", "user1@usr.org");
usrData.put("password", "ChangeZbadPa$$w0rd");
usrData.put("domainid", "0");
Response clientResponse = target("/v1/users").request().post(entity(usrData));
Response clientResponse = target("/v1/users")
.request()
.post(entity(usrData));
assertEquals(201, clientResponse.getStatus());
// check create user missing name data
@ -78,13 +79,71 @@ public class UserHandlerTest extends HandlerTest {
assertEquals(500, e.getResponse().getStatus());
}
// check update user data
// check create user missing enable data and with long name
usrData.remove("enable");
usrData.put("name", getLongName());
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(400, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
// check create user missing domain data and too long
usrData.put("name", "usr1Update");
clientResponse = target("/v1/users/1").request().put(entity(usrData));
assertEquals(200, clientResponse.getStatus());
usrData.remove("domainid");
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(400, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("domainid", getLongName());
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(400, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("domainid", "0");
// check create user description data too long
usrData.put("description", getLongName());
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(400, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("description", "Test user");
// check create user missing email data and too long
usrData.remove("email");
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(201, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("email", getLongName());
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(400, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("email", "user1@usr.org");
// check create user missing password data and too long
usrData = checkPasswordError(usrData);
//check update user
checkPutMethod(usrData);
usr = target("/v1/users/1").request().get(User.class);
assertNotNull(usr);
assertTrue(usr.getName().equals("usr1Update"));
assertEquals("usr1Update", usr.getName());
// check delete user
clientResponse = target("/v1/users/1").request().delete();
@ -101,8 +160,8 @@ public class UserHandlerTest extends HandlerTest {
// Bug 8382: if a user id is specified, 400 is returned
usrData = new HashMap<>();
usrData.put("name", "usr1");
usrData.put("description", "test user");
usrData.put("enabled", "true");
// usrData.put("description", "test user");
// usrData.put("enabled", "true");
usrData.put("email", "user1@usr.org");
usrData.put("password", "ChangeZbadPa$$w0rd");
usrData.put("userid", "userid");
@ -110,13 +169,114 @@ public class UserHandlerTest extends HandlerTest {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(400, clientResponse.getStatus());
}
private Map<String, Object> checkPasswordError(Map<String, Object> usrData) {
usrData.remove("password");
Response clientResponse;
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(407, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("password", getLongName());
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(400, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("password", "");
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(407, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("password", "111");
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(407, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("password", "12434356");
try {
clientResponse = target("/v1/users").request().post(entity(usrData));
assertEquals(407, clientResponse.getStatus());
} catch (WebApplicationException e) {
assertEquals(500, e.getResponse().getStatus());
}
usrData.put("password", "ChangeZbadPa$$w0rd");
return usrData;
}
private Map<String, Object> checkPutMethod(Map<String, Object> usrData) {
// check update user data
usrData.put("name", getLongName());
Response clientResponse = target("/v1/users/1").request().put(entity(usrData));
assertEquals(400, clientResponse.getStatus());
// check update user data with long pwd
usrData.put("password", getLongName());
clientResponse = target("/v1/users/1").request().put(entity(usrData));
assertEquals(400, clientResponse.getStatus());
// check update user data
usrData.put("description", getLongName());
clientResponse = target("/v1/users/1").request().put(entity(usrData));
assertEquals(400, clientResponse.getStatus());
// check update user data
usrData.put("email", getLongName());
clientResponse = target("/v1/users/1").request().put(entity(usrData));
assertEquals(400, clientResponse.getStatus());
// check update user data
usrData.put("domainid",getLongName());
clientResponse = target("/v1/users/1").request().put(entity(usrData));
assertEquals(400, clientResponse.getStatus());
// check update user data
usrData.put("description", "Test user");
usrData.put("email", "user1@usr.org");
usrData.put("password", "ChangeZbadPa$$w0rd");
usrData.put("domainid", "0");
usrData.put("name", "usr1Update");
clientResponse = target("/v1/users/101").request().put(entity(usrData));
assertEquals(404, clientResponse.getStatus());
clientResponse = target("/v1/users/1").request().put(entity(usrData));
assertEquals(200, clientResponse.getStatus());
return usrData;
}
private String getLongName() {
return "abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn" +
"abcdefg1234567890vbnabcdefg1234567890vbn";
}
}
/**
* Revision history
*
* <p>
* -------------------------------------------------------------------------
* Date Author Note
*
* <p>
* -------------------------------------------------------------------------
* 2019/7/3 Dong Xiancun creat
*/

View File

@ -135,7 +135,7 @@
aliyun
-->
<repository>
<id>ali</id>
<id>public-repo-net</id>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<releases>
<enabled>true</enabled>
@ -181,7 +181,7 @@
</repositories>
<pluginRepositories>
<pluginRepository>
<id>ali</id>
<id>public-repo-net</id>
<name>aliyun-pluginRepository</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<releases>

View File

@ -162,11 +162,14 @@ endif
ulog:
ifeq ($(OPT), clean)
$(MLOG)make $(MAKE_FLAGS) -C Platform/build -f user.ulog.syslog_sched.Makefile cleanall MLOG=$(MLOG) MAKE_TARGET=syslog-sched
$(MLOG)make $(MAKE_FLAGS) -C Platform/build -f user.ulog.api.Makefile cleanall MLOG=$(MLOG) MAKE_TARGET=ulog-api
$(MLOG)make $(MAKE_FLAGS) -C Platform/build -f user.ulog.log_sched.Makefile cleanall MLOG=$(MLOG) MAKE_TARGET=log-sched
else ifeq ($(OPT), install)
$(MLOG)make $(MAKE_FLAGS) -C Platform/build -f user.ulog.syslog_sched.Makefile install DIR=$(DIR) MLOG=$(MLOG) MAKE_TARGET=syslog-sched
$(MLOG)make $(MAKE_FLAGS) -C Platform/build -f user.ulog.api.Makefile install DIR=$(DIR) MLOG=$(MLOG) MAKE_TARGET=ulog-api
$(MLOG)make $(MAKE_FLAGS) -C Platform/build -f user.ulog.log_sched.Makefile install DIR=$(DIR) MLOG=$(MLOG) MAKE_TARGET=log-sched
else
$(MLOG)make all $(MAKE_FLAGS) -C Platform/build -f user.ulog.syslog_sched.Makefile MLOG=$(MLOG) DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=syslog-sched
$(MLOG)make all $(MAKE_FLAGS) -C Platform/build -f user.ulog.api.Makefile MLOG=$(MLOG) DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=ulog-api
$(MLOG)make all $(MAKE_FLAGS) -C Platform/build -f user.ulog.log_sched.Makefile MLOG=$(MLOG) DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=log-sched
endif
database:

View File

@ -0,0 +1,66 @@
# target name, the target name must have the same name of c source file
TARGET_NAME=libulogapi
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = DLL
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
# custom install dir
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_LINUX ?= TRUE
PLAT_ARM64 ?= TRUE
VPATH = ../user/ulog/ulog-api
# source code
# set the source file, don't used .o because of ...
COMMON_SRCS = ulog_api.c
# MRS Board Source Files
PLAT_LINUX_SRCS = $(COMMON_SRCS)
PLAT_ARM64_SRCS = $(COMMON_SRCS)
# gcc CFLAGS
PLAT_ARM64_CFLAGS := -fPIC -I../../Common -I../user/ulog
PLAT_LINUX_CFLAGS := $(PLAT_ARM64_CFLAGS)
PLAT_ARM64_LDFLAGS := -fPIC -shared
PLAT_LINUX_LDFLAGS := $(PLAT_ARM64_LDFLAGS)
#gcc libs
# this line must be at below of thus, because of...
include ../../Common/common.Makefile
ifneq ($(MAKECMDGOALS), clean)
ifneq ($(MAKECMDGOALS), cleanall)
ifneq ($(notdir $(DEPEND_LIB)), $(wildcard $(DEPEND_LIB)))
$(shell $(CP) $(DEPEND_LIB) ./)
endif
endif
endif
ifeq ($(MAKECMDGOALS), )
$(shell find ./ -name "$(TARGET)-*.ko" -delete)
else
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.ko" -delete)
endif
endif

View File

@ -0,0 +1,76 @@
# target name, the target name must have the same name of c source file
TARGET_NAME=log-sched
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = EXE
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
# custom install dir
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_LINUX ?= TRUE
PLAT_ARM64 ?= TRUE
VPATH = ../user/ulog/log-sched
# source code
# set the source file, don't used .o because of ...
COMMON_SRCS = log_file.c log_console.c log_common.c log_sched.c
# MRS Board Source Files
PLAT_LINUX_SRCS = $(COMMON_SRCS)
PLAT_ARM64_SRCS = $(COMMON_SRCS)
# gcc CFLAGS
PLAT_ARM64_CFLAGS := -fPIC -I../../Common -I../common/rpc -I../user/ulog
PLAT_LINUX_CFLAGS := $(PLAT_ARM64_CFLAGS)
PLAT_ARM64_LDFLAGS := -lpthread
PLAT_LINUX_LDFLAGS := $(PLAT_ARM64_LDFLAGS)
#gcc libs
ARM64_LIBS := ./libopenrpc-arm64.so ./libulogapi-arm64.so ../thirdparty/arm64/libev-arm64.so
LINUX_LIBS := ./libopenrpc-linux.so ./libulogapi-linux.so ../thirdparty/x86_64/libev-linux.so
ifeq ($(PLAT_ARM64), TRUE)
DEPEND_LIB += ./debug/libopenrpc-arm64.so ./debug/libulogapi-arm64.so
USER_CLEAN_ITEMS += ./libopenrpc-arm64.so ./libulogapi-arm64.so
endif
ifeq ($(PLAT_LINUX), TRUE)
DEPEND_LIB += ./debug/libopenrpc-linux.so ./debug/libulogapi-linux.so
USER_CLEAN_ITEMS += ./libopenrpc-linux.so ./libulogapi-linux.so
endif
# this line must be at below of thus, because of...
include ../../Common/common.Makefile
ifneq ($(MAKECMDGOALS), clean)
ifneq ($(MAKECMDGOALS), cleanall)
ifneq ($(notdir $(DEPEND_LIB)), $(wildcard $(DEPEND_LIB)))
$(shell $(CP) $(DEPEND_LIB) ./)
endif
endif
endif
ifeq ($(MAKECMDGOALS), )
$(shell find ./ -name "$(TARGET)-*.ko" -delete)
else
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.ko" -delete)
endif
endif

View File

@ -7,6 +7,8 @@
#define MODULE_NAME_LEN 32
#define IP_STR_LEN 32
#define RPC_MODULE_SYSLOG_NAME "syslog-schedule-rpc"
struct _rpc_module {
char module_name[MODULE_NAME_LEN];
char host[IP_STR_LEN];
@ -18,7 +20,8 @@ typedef struct _rpc_module rpc_module;
#define MODULE_REG_ARRAY \
{ \
{"ConfigManger#0", "127.0.0.1", 10002, 1} \
{"ConfigManger#0", "127.0.0.1", 10002, 1}, \
{RPC_MODULE_SYSLOG_NAME, "127.0.0.1", 10003, 2} \
}
#endif /* RPC_MODULE_H_ */

View File

@ -302,7 +302,7 @@ int update_database(int module_id, void * db_handle, int op_type, char * tabl
* table_name -
* sql_str - SQL语句
* begin_num -
* need_num -
* need_num - , need_num = 0
* param_num - 0SQL注入问题使
* Output:
*  return_num -
@ -341,7 +341,7 @@ void * select_datebase_by_number(int module_id, void * db_handle, char * table_
return NULL;
}
if ((begin_num <= 0) || (need_num <= 0))
if ((begin_num <= 0) || (need_num < 0))
{
return NULL;
}
@ -447,6 +447,12 @@ void * select_datebase_by_number(int module_id, void * db_handle, char * table_
}
json = cJSON_CreateObject();
if (NULL == json)
{
SQLCloseCursor(hstmt);
SQLFreeStmt(hstmt, SQL_DROP);
return NULL;
}
/* 将应用程序数据缓冲区绑定到结果集中的列 */
for (i = 1; i <= column_nmuber; i++)
@ -474,10 +480,16 @@ void * select_datebase_by_number(int module_id, void * db_handle, char * table_
/* 查询结果 */
FetchOrientation = SQL_FETCH_RELATIVE;
for (i = 1; i <= need_num; i++)
/* need_num为0表示一次返回所有找到的信息 */
if (0 == need_num)
{
while(1)
{
ret = SQLFetchScroll(hstmt, FetchOrientation, begin_num);
FetchOrientation = SQL_FETCH_NEXT;
/* 查找失败,表示已经返回所有找到的信息 */
if (ret != SQL_SUCCESS)
{
break;
@ -503,11 +515,52 @@ void * select_datebase_by_number(int module_id, void * db_handle, char * table_
}
else
{
/* 不支持类型,后续增加统计和打印 */
}
}
}
}
else
{
for (i = 1; i <= need_num; i++)
{
ret = SQLFetchScroll(hstmt, FetchOrientation, begin_num);
FetchOrientation = SQL_FETCH_NEXT;
/* 查找失败,表示已经返回所有找到的信息 */
if (ret != SQL_SUCCESS)
{
break;
}
ret_num++;
cJSON_AddItemToArray(array, obj = cJSON_CreateObject());
for (j = 1; j <= column_nmuber; j++)
{
if (SQL_BIGINT == db_column_info[j].dateType)
{
cJSON_AddNumberToObject(obj, db_column_info[j].name, *((long long *)&(value[j][0])));
}
else if (SQL_CHAR == db_column_info[j].dateType)
{
cJSON_AddStringToObject(obj, db_column_info[j].name , value[j][0]);
}
else if (SQL_DOUBLE == db_column_info[j].dateType)
{
cJSON_AddNumberToObject(obj, db_column_info[j].name , *((double *)&(value[j][0])));
}
else
{
/* 不支持类型,后续增加统计和打印 */
}
}
}
}
SQLCloseCursor(hstmt);
SQLFreeStmt(hstmt, SQL_DROP);

View File

@ -0,0 +1,100 @@
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include "ulog.h"
#include "log_common.h"
#define FILTER_CONTENT ":msg,contains,\""MODULE_FMT"\"\n"
#define BAK_FILE "/tmp/%s"
int write_log_conf(const u8 level, const char *conf_path, const char *conf_file,
const char *rediect_path, const char *filter_mod)
{
FILE *fp = NULL;
int ret = 1;
u8 exist_backup = 1;
/********** rsyslog configure **********/
char conf_path_file[MAX_LINE_SIZE];
snprintf(conf_path_file, sizeof(conf_path_file), "%s%s", conf_path, conf_file);
char bak_file[MAX_LINE_SIZE];
snprintf(bak_file, sizeof(bak_file), BAK_FILE, conf_file);
if (rename(conf_path_file, bak_file) < 0) {
if (errno == ENOENT) {
exist_backup = 0;
ULOG_INFO(g_log, "Been not exist, Configure file:%s is need to backup");
} else {
ULOG_ERR(g_log, "Baking configure file:%s is failure:%s %d", conf_path_file, strerror(errno), errno);
return ret;
}
}
fp = fopen(conf_path_file, "w");
if (fp == NULL) {
ULOG_ERR(g_log, "Opening log configure file:%s is failure:%s", conf_path_file, strerror(errno));
goto END;
}
int i;
char line[MAX_LINE_SIZE + 100] = {0};
if ((filter_mod != NULL) && (strlen(filter_mod) > 0)) {
snprintf(line, sizeof(line), FILTER_CONTENT, filter_mod);
if (fputs(line, fp) == EOF) {
ULOG_ERR(g_log, "Message filter:%s of configure file which is written is failure:%s",
filter_mod, strerror(errno));
goto END;
}
}
char tmp[20];
line[0] = '\0'; // 清零
for (i = 0; i <= level;) {
if (snprintf(tmp, sizeof(tmp), "*.=%s", g_level_array[i].str) < 0) {
ULOG_ERR(g_log, "Setting content of log file configure is failure");
goto END;
}
strcat(line, tmp);
i++;
if (level >= i) {
strcat(line, ";");
}
}
strcat(line, " ");
strcat(line, rediect_path);
if (fputs(line, fp) == EOF) {
ULOG_ERR(g_log, "Configure file which is written is failure:%s", strerror(errno));
goto END;
}
ret = 0;
END:
if (fp != NULL) {
fclose(fp);
}
if ((ret == 1) && (exist_backup == 1)) {
// 回复备份配置
if (rename(bak_file, conf_path_file) < 0) {
ULOG_ERR(g_log, "Restoring configure file:%s is failure:%s", conf_path_file, strerror(errno));
}
}
return ret;
}
int modify_authorizing(const char *redirect_path)
{
if (chmod(redirect_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0) {
ULOG_ERR(g_log, "Authorizing of %s which is modified is failure:%s", strerror(errno));
return 1;
}
return 0;
}

View File

@ -0,0 +1,32 @@
#ifndef _LOG_COMMON_H
#define _LOG_COMMON_H
#include "ulog_api.h"
#define MAX_LINE_SIZE 1024
#define LOG_CONF_PATH "/etc/rsyslog.d/"
typedef struct _level_str {
u32 level;
char str[10];
} level_str_t;
extern ulog_t *g_log;
static level_str_t g_level_array[] = {
{LOG_EMERG, "emerg"},
{LOG_ALERT, "alert"},
{LOG_CRIT, "crit"},
{LOG_ERR, "err"},
{LOG_WARNING, "warn"},
{LOG_NOTICE, "notice"},
{LOG_INFO, "info"},
{LOG_DEBUG, "debug"}
};
int write_log_conf(const u8 level, const char *conf_path, const char *conf_file,
const char *rediect_path, const char *filter_mod);
int modify_authorizing(const char *redirect_path);
#endif

View File

@ -0,0 +1,35 @@
#include "log_console.h"
#include "log_common.h"
#define LOG_CONF_COSOLE_FILE_NAME "log-console.conf"
#define LOG_REDIRECT_CONSOLE "/dev/console"
static int config_log_console(const log_console_t *conf)
{
if (write_log_conf(conf->level, LOG_CONF_PATH, LOG_CONF_COSOLE_FILE_NAME, LOG_REDIRECT_CONSOLE, conf->module_name) != 0) {
ULOG_ERR(g_log, "configure of log conosle which is written is failure");
return 1;
}
if (modify_authorizing(LOG_REDIRECT_CONSOLE) != 0) {
ULOG_ERR(g_log, "Modifying authorizing of %s is failure", LOG_REDIRECT_CONSOLE);
return 1;
}
return 0;
}
void rpc_conf_log_console(rpc_conn *conn, pointer input, int input_len, pointer data)
{
u32 need_len = sizeof(log_console_t);
if (input_len < need_len) {
ULOG_WARNING(g_log,
"The input paramter of rpc log console is needed length of %u, but the actual length is %u",
need_len, input_len);
return;
}
config_log_console((const log_console_t *)input);
}

View File

@ -0,0 +1,16 @@
#ifndef _LOG_CONSOLE_H
#define _LOG_CONSOLE_H
#include "ulog_api.h"
#include "common_types.h"
#include "rpc_common.h"
typedef struct _log_console {
u8 level;
u8 on;
char module_name[MAX_MODULE_NAME_SZ];
} log_console_t;
void rpc_conf_log_console(rpc_conn *conn, pointer input, int input_len, pointer data);
#endif

View File

@ -0,0 +1,137 @@
#include <string.h>
#include <errno.h>
#include "log_file.h"
#include "log_common.h"
#define LOG_CONF_FILE_NAME "log-file.conf"
#define LOG_LOGRATATE_FILE_NAME "/etc/logrotate.d/log-syslog"
#define DEFAULT_LOG_FILE "/var/log/syslog-test"
#define DEFAULT_LOG_DEL_OVER_DAYS (30 * 6)
#define LOGROTATE_CONF "%s\n" \
"{\n" \
" rotate %u\n" \
" daily\n" \
" missingok\n" \
"%s" \
" postrotate\n" \
" /usr/lib/rsyslog/rsyslog-rotate\n" \
" endscript\n" \
"}"
#define STR_COMPRESS " compress\n"
/*
typedef struct _level_str {
u32 level;
char str[10];
} level_str_t;
static level_str_t g_level_array[] = {
{LOG_EMERG, "emerg"},
{LOG_ALERT, "alert"},
{LOG_CRIT, "crit"},
{LOG_ERR, "err"},
{LOG_WARNING, "warn"},
{LOG_NOTICE, "notice"},
{LOG_INFO, "info"},
{LOG_DEBUG, "debug"}
};
*/
#define MAX_LOG_LEVEL_VALUE (sizeof(g_level_array) / sizeof(level_str_t))
static int write_logratate_conf(const log_file_t *conf, const char *log_path)
{
int ret = 1;
FILE *fp = NULL;
/********** logrotate **********/
char str_compress[sizeof(STR_COMPRESS)] = {0};
if (conf->is_compress == LOG_COMPRESS) {
strncpy(str_compress, STR_COMPRESS, sizeof(str_compress));
}
u32 days = DEFAULT_LOG_DEL_OVER_DAYS;
if (conf->del_over_days > 0) {
days = conf->del_over_days;
}
char line[1024] = {0};
if (snprintf(line, sizeof(line), LOGROTATE_CONF, log_path, days, str_compress) < 0) {
ULOG_ERR(g_log, "Setting content of logratote is failure");
goto END;
}
fp = fopen(LOG_LOGRATATE_FILE_NAME, "w");
if (fp == NULL) {
ULOG_ERR(g_log, "Opening logratate file:%s is failure:%s", LOG_CONF_FILE_NAME, strerror(errno));
goto END;
}
if (fputs(line, fp) == EOF) {
ULOG_ERR(g_log, "Configure file of logratate which is written is failure:%s", strerror(errno));
goto END;
}
ret = 0;
END:
if (fp != NULL) {
fclose(fp);
}
return ret;
}
static int conf_log_file(const log_file_t *conf)
{
int ret = 1;
u32 max_level = MAX_LOG_LEVEL_VALUE;
if (conf->level > max_level) {
ULOG_WARNING(g_log, "Configure log level:%u more than max value:%u", conf->level, max_level);
return 1;
}
char path[sizeof(conf->path)];
if (strlen(conf->path) > 0) {
strncpy(path, conf->path, sizeof(path));
} else {
strncpy(path, DEFAULT_LOG_FILE, sizeof(path));
}
if (write_log_conf(conf->level, LOG_CONF_PATH, LOG_CONF_FILE_NAME, path, NULL) != 0) {
ULOG_ERR(g_log, "Log configure which is written is failure");
return 1;
}
/********** logrotate **********/
if (write_logratate_conf(conf, path) != 0) {
ULOG_ERR(g_log, "Logratate configure which is written is failure");
return 1;
}
if (conf->del_over_size > 0) {
}
return ret;
}
void rpc_conf_log_file(rpc_conn *conn, pointer input, int input_len, pointer data)
{
u32 need_len = sizeof(log_file_t);
if (input_len < need_len) {
ULOG_WARNING(g_log,
"The input paramter of rpc log file is needed length of %u, but the actual length is %u",
need_len, input_len);
return;
}
conf_log_file((const log_file_t *)input);
//rpc_return_null(conn);
}

View File

@ -0,0 +1,29 @@
#ifndef __LOG_H
#define __LOG_H
#include <syslog.h>
#include <linux/limits.h>
#include "common_types.h"
#include "rpc_common.h"
#include "log_common.h"
#define MAX_LOG_PATH MAX_LINE_SIZE
typedef enum {
LOG_UNCOMPRESS = 0,
LOG_COMPRESS
} log_compress_t;
typedef struct _log_file {
u8 level;
char path[MAX_LOG_PATH];
log_compress_t is_compress;
u32 del_over_days;
u64 del_over_size;
} log_file_t;
void rpc_conf_log_file(rpc_conn *conn, pointer input, int input_len, pointer data);
#endif

View File

@ -0,0 +1,72 @@
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "rpc_server.h"
#include "ulog_api.h"
#include "log_file.h"
#include "log_console.h"
#include "rpc_module.h"
#define LOG_SCHED_MODULE_NAME "log-sched"
#define SERVICE_LOG_FILE_NAME "log-file"
ulog_t *g_log = NULL;
int main(int argc, char **argv)
{
int run_daemon = 0;
char *options = "d";
int opt;
while ((opt = getopt(argc, argv, options)) != -1) {
switch (opt) {
case 'd':
run_daemon = 1;
break;
}
}
g_log = ulog_init(LOG_SCHED_MODULE_NAME, !run_daemon);
if (g_log == NULL) {
fprintf(stderr, "Initiating ulog is failure");
return 1;
}
if (run_daemon) {
if (daemon(0, 0) == -1) {
ULOG_ERR(g_log, "Setting daemon running is failure:%s", strerror(errno));
goto END;
}
}
rpc_server *server = rpc_server_create_ex(RPC_MODULE_SYSLOG_NAME);
if (server == NULL)
{
ULOG_ERR(g_log, "start server error");
return 1;
}
ULOG_INFO(g_log, "Server of log schedule is started");
/* 注册配置处理函数 */
rpc_server_regservice(server, SERVICE_LOG_FILE_NAME, "conf_log_file", rpc_conf_log_file);
log_file_t log = {0};
log.is_compress = LOG_UNCOMPRESS; //LOG_COMPRESS;
log.del_over_days = 10;
log.level = LOG_DEBUG;
rpc_conf_log_file(NULL, &log, sizeof(log), NULL);
log_console_t console = {0};
strcpy(console.module_name, "111");
console.level = LOG_DEBUG;
console.on = 1;
rpc_conf_log_console(NULL, &console, sizeof(console), NULL);
END:
ulog_close(g_log);
return 0;
}

View File

@ -1,7 +0,0 @@
#include "log_file.h"
int conf_log_file(rpc_conn *conn, pointer input, int input_len, pointer data)
{
return 0;
}

View File

@ -1,20 +0,0 @@
#ifndef __LOG_H
#define __LOG_H
#include <linux/limits.h>
#include "common_types.h"
#include "rpc_common.h"
typedef struct _log_file {
u8 level;
char path[PATH_MAX];
u32 compress_over_days;
u32 del_over_days;
u64 compress_over_size;
u64 del_over_size;
} log_file_t;
int conf_log_file(rpc_conn *conn, pointer input, int input_len, pointer data);
#endif

View File

@ -1,41 +0,0 @@
#include <stdio.h>
#include <unistd.h>
#include "log_file.h"
#define SYSLOG_SCHED_RPC_NAME "syslog_schedule_rpc"
#define SERVICE_LOG_FILE_NAME "log_file"
int main(int argc, char **argv)
{
int run_daemon = 0;
char *options = "d";
int opt;
while ((opt = getopt(argc, argv, options)) != -1) {
switch (opt) {
case 'd':
run_daemon = 1;
break;
}
}
if (run_daemon) {
if (daemon(0, 0) == -1) {
return 1;
}
}
rpc_server *server = rpc_server_create_ex(SYSLOG_SCHED_RPC_NAME);
if (server = NULL)
{
printf("start server error\n");
return 1;
}
printf("Server of log schedule is started\n");
/* 注册配置处理函数 */
rpc_server_regservice(server, SERVICE_LOG_FILE_NAME, "conf_log_file", conf_log_file);
}

View File

@ -0,0 +1,58 @@
#include <stdio.h>
#include <stdarg.h>
#include "ulog.h"
#include "common_types.h"
#include "ulog_api.h"
#define LOG_MSG_SZ 1024
ulog_t *ulog_init(const char *module_name, u8 is_print)
{
ulog_t *log;
u32 len = strlen(module_name);
if (len > MAX_MODULE_NAME_SZ) {
fprintf(stderr, "The length:%d of module_name can't more than %d", len, MAX_MODULE_NAME_SZ);
return NULL;
}
log = (ulog_t *)malloc(sizeof(*log));
if (log == NULL) {
fprintf(stderr, "Allocating log memory is failure");
return NULL;
}
strncpy(log->module_name, module_name, len);
int opt = LOG_PERROR |LOG_PID;
if (is_print > 0) {
opt |= LOG_CONS;
}
openlog(log->module_name, opt, LOG_USER);
return log;
}
void ulog_close(ulog_t *log)
{
if (log != NULL) {
free(log);
}
closelog();
}
void ulog_record(const ulog_t *log, int level, const char *fmt, ...)
{
if (log == NULL) {
fprintf(stderr, "Log is null");
return;
}
char log_buf[LOG_MSG_SZ];
va_list args;
va_start(args, fmt);
vsnprintf(log_buf, sizeof(log_buf), fmt, args);
va_end(args);
syslog(level, MODULE_FMT" %s", log->module_name, log_buf);
}

6
Platform/user/ulog/ulog.h Executable file
View File

@ -0,0 +1,6 @@
#ifndef _ULOG_H
#define _ULOG_H
#define MODULE_FMT "[%s]"
#endif

View File

@ -1,5 +1,5 @@
# target name, the target name must have the same name of c source file
TARGET_NAME=syslog-sched
TARGET_NAME=webauth
# target
# for linux module driver: KO
@ -19,40 +19,41 @@ TARGET_BOX =
DEBUG = TRUE
PLAT_LINUX ?= TRUE
PLAT_ARM64 ?= TRUE
PLAT_ARM64 ?= FALSE
VPATH = ../user/ulog/syslog-schedule
VPATH = ../user/user_auth ../user/user_manager/usermanager-auth
# source code
# set the source file, don't used .o because of ...
COMMON_SRCS = log_file.c log_sched.c
COMMON_SRCS = web_auth.c user_hashtable.c user_auth.c
# MRS Board Source Files
PLAT_LINUX_SRCS = $(COMMON_SRCS)
PLAT_ARM64_SRCS = $(COMMON_SRCS)
# gcc CFLAGS
PLAT_ARM64_CFLAGS := -fPIC -I../../Common -I../common/rpc
PLAT_ARM64_CFLAGS := -I../../Common -I../../Platform/common -I../../Product/user -I../../Product/common
PLAT_LINUX_CFLAGS := $(PLAT_ARM64_CFLAGS)
PLAT_ARM64_LDFLAGS := -lpthread
PLAT_ARM64_LDFLAGS :=
PLAT_LINUX_LDFLAGS := $(PLAT_ARM64_LDFLAGS)
#gcc libs
ARM64_LIBS := ./libopenrpc-arm64.so ../thirdparty/arm64/libev-arm64.so
LINUX_LIBS := ./libopenrpc-linux.so ../thirdparty/x86_64/libev-linux.so
ARM64_LIBS := ./userauthapi-arm64.so
LINUX_LIBS := -lcjson ./userauthapi-linux.so
ifeq ($(PLAT_ARM64), TRUE)
DEPEND_LIB += ./debug/libopenrpc-arm64.so
USER_CLEAN_ITEMS += ./libopenrpc-arm64.so
DEPEND_LIB += ./debug/userauthapi-arm64.so
USER_CLEAN_ITEMS += ./userauthapi-arm64.so
endif
ifeq ($(PLAT_LINUX), TRUE)
DEPEND_LIB += ./debug/libopenrpc-linux.so
USER_CLEAN_ITEMS += ./libopenrpc-linux.so
DEPEND_LIB += ./debug/userauthapi-linux.so
USER_CLEAN_ITEMS += ./userauthapi-linux.so
endif
# this line must be at below of thus, because of...

View File

@ -1,116 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "hlist.h"
#include "user_hashtable.h"
struct hlist_head *hash;
struct hlist_node *p = NULL, *n = NULL ;
int i = 0;
USER_INFO *pNode ;
/*计算hash值 */
struct hlist_head *call_hash(struct hlist_head *hash, uint32_t ip)
{
unsigned int val = ip % 100;
return &hash[val];
}
/*初始化函数 */
int Init_hash()
{
hash = (struct hlist_head*)malloc(sizeof(*hash)*100);
if(NULL == hash)
{
printf("alloc error\n");
return -1;
}
for(i = 0; i < 100; i++)
INIT_HLIST_HEAD(&hash[i]);
}
/*查找用户信息*/
struct user_info *ufind_user(uint32_t user_ip)
{
hlist_for_each_safe(p,n,call_hash(hash,user_ip))
{
pNode = hlist_entry(p, struct user_info ,hnode);
if(pNode != NULL)
printf("user_id :%d\n",pNode->id);
return pNode;
}
}
/*增加用户信息*/
int uadd_user(uint32_t user_ip, int user_id)
{
USER_INFO *pNode =NULL;
hlist_for_each_safe(p,n,call_hash(hash, user_ip)) /*查找ip是否存在hash表中 */
{
pNode = hlist_entry(p, struct user_info ,hnode);
if(pNode != NULL)
printf("IP ALEADY EXISTED\n");
}
if (pNode == NULL)
{
pNode = (struct user_info *)malloc(sizeof(struct user_info));
if (NULL == pNode)
{
return -1;
}
memset(pNode,0,sizeof(struct user_info));
INIT_HLIST_NODE(&pNode->hnode);
pNode->ip = user_ip;
hlist_add_head(&pNode->hnode, call_hash(hash, user_ip));
}
pNode->id = user_id;
}
/*删除用户信息 */
void udelete_user(int user_ip)
{
hlist_for_each_safe(p,n,call_hash(hash,user_ip))
{
pNode = hlist_entry(p, struct user_info ,hnode);
hlist_del(&pNode->hnode);
free(pNode);
}
}
/*删除所有的hash节点 */
void udelete_all()
{
for(i = 0; i < 100; i++)
{
hlist_for_each_safe(p,n,&hash[i])
{
pNode = hlist_entry(p, struct user_info ,hnode);
hlist_del(&pNode->hnode);
free(pNode);
}
}
}
/*打印所有信息信息 */
void uprintf_users()
{
for(i = 0; i < 100; i++)
{
hlist_for_each_safe(p,n,&hash[i])
{
char str[32];
pNode = hlist_entry(p, struct user_info ,hnode);
if(pNode != NULL)
inet_ntop(AF_INET, (void *)&pNode->ip, str, 32);
printf("user_ip :%s user_id:%d\n", str, pNode->id);
}
}
}

View File

@ -0,0 +1,181 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "hlist.h"
#include "user_hashtable.h"
#include "user_auth.h"
extern USER_AUTH_LIST g_user_auth_ret_table[] ;
/*链表全局变量 */
struct hlist_head *hash;
USER_INFO *pNode ;
/*计算hash值 */
struct hlist_head * call_hash(struct hlist_head *hash, uint32_t ip)
{
unsigned int val = ip % 100;
printf("val =%d\n", val);
return &hash[val];
}
/*初始化函数 */
int Init_hash()
{
int i = 0;
/*创建hash头 */
hash = (struct hlist_head*)malloc(sizeof(*hash)*100);
if(NULL == hash)
{
printf("alloc error\n");
return -1;
}
/*初始化hash表头 */
for(i = 0; i < 100; i++)
INIT_HLIST_HEAD(&hash[i]);
/*hsah桶普通节点分配内存 */
pNode = (struct user_info *)malloc(sizeof(struct user_info));
if (NULL == pNode)
{
printf("alloc error\n");
return -1;
}
/*初始化hash桶的普通结点 */
memset(pNode,0,sizeof(struct user_info));
INIT_HLIST_NODE(&pNode->hnode);
}
/*查找用户信息*/
USER_INFO * ufind_user(uint32_t user_ip)
{
struct hlist_node *p = NULL, *n = NULL ;
/* 这个实际上就是一个for循环从头到尾遍历链表。
* posstruct hlist_node类型的一个指针
* nstruct hlist_node类型的一个指针
* headstruct hlist_head类型的一个指针hlist链表的头结点
*/
hlist_for_each_safe(p,n,call_hash(hash,user_ip))
{
/* p表示struct hlist_node类型的一个地址。
* struct user_info
* hnodetype结构体中的hlist_node成员变量的名称
* p所指地址的这个结构体的首地址
*/
pNode = hlist_entry(p, struct user_info ,hnode);
if(pNode != NULL)
printf("user_id :%d\n",pNode->id);
return pNode;
}
}
/*增加用户信息*/
int uadd_user(uint32_t user_ip, int user_id)
{
struct hlist_node *pos = NULL, *n = NULL ;
pNode = NULL;
struct hlist_head* pVal = call_hash(hash, user_ip);
printf("pVal = %p, pVal->first = %p\n", pVal, pVal->first);
//hlist_for_each_safe(p,n,call_hash(hash, user_ip)) /*查找ip是否存在hash表中 */
for (pos = pVal->first; pos && ({ n = pos->next; 1; }); pos = n)
{
pNode = hlist_entry(pos, struct user_info ,hnode);
if(pNode != NULL)
printf("IP ALEADY EXISTED\n");
}
if (pNode == NULL)
{
pNode = (struct user_info *)malloc(sizeof(struct user_info));
if (NULL == pNode)
{
return -1;
}
memset(pNode,0,sizeof(struct user_info));
INIT_HLIST_NODE(&pNode->hnode);
pNode->ip = user_ip;
hlist_add_head(&pNode->hnode, call_hash(hash, user_ip));
}
pNode->id = user_id;
}
/*删除用户信息 */
void udelete_user(int user_ip)
{
struct hlist_node *p = NULL, *n = NULL ;
int i = 0;
unsigned short check_id;
hlist_for_each_safe(p,n,call_hash(hash,user_ip))
{
pNode = hlist_entry(p, struct user_info ,hnode);
/*查找用户ID确认ID是否存在 */
check_id = g_user_auth_ret_table[pNode->id].group_id;
if(check_id != NULL)
{
hlist_del(&pNode->hnode);
}
free(pNode);
}
}
/*删除所有的hash节点 */
void udelete_all()
{
struct hlist_node *p = NULL, *n = NULL ;
int i = 0;
for(i = 0; i < 100; i++)
{
hlist_for_each_safe(p,n,&hash[i])
{
pNode = hlist_entry(p, struct user_info ,hnode);
hlist_del(&pNode->hnode);
free(pNode);
}
}
}
/*打印所有信息信息 */
void uprintf_users()
{
struct hlist_node *p = NULL, *n = NULL ;
int i = 0;
for(i = 0; i < 100; i++)
{
hlist_for_each_safe(p,n,&hash[i])
{
char str[32];
pNode = hlist_entry(p, struct user_info ,hnode);
if(pNode != NULL)
inet_ntop(AF_INET, (void *)&pNode->ip, str, 32);
printf("user_ip :%s user_id:%d\n", str, pNode->id);
}
}
}

View File

@ -0,0 +1,170 @@
#include <stdio.h>
#include <string.h>
#include <cjson/cJSON.h>
#include "web_auth.h"
#include "user_hashtable.h"
/*输入参数:用户名、密码,json格式*/
/*输出参数resultcode、描述信息message、剩余锁定时间remain_lock_time(认证成功和失败的情况下剩余锁定时间默认为0) */
/*location:url location之后get方法判断是否是get方法 url的时候要判断下这个用户是否已经认证过*/
/* 用户认证 */
void user_auth_login(char* username, char* password, USER_AUTH_RET* auth_result);
char * mes[]={"SUCCESS", "ErrorUsernameOrpassword", "NotInVaildTime",
"OutMaxOnlineNum", "UserIsLocked", "LackConfigInfo",
"OverMaxOnlineNum", "OtherErr"};
/*content形式 {"username":"adimn", "password":"admin"} */
ret_code user_auth(pointer content, RESULT *uresult)
{
ret_code ret = RET_OK;
cJSON *cjson;
USER_AUTH_RET *resultinfo;
time_t time = 0;
memset(uresult, 0, sizeof(RESULT));
/*创建内存地址 */
resultinfo = (USER_AUTH_RET *)malloc(sizeof(USER_AUTH_RET));
if (NULL == resultinfo)
{
ret = RET_NOMEM;
return ret;
}
/*JSON字符串到JSON格式 */
cjson = cJSON_Parse(content);
if(!cjson)
{
ret = RET_INPUTERR;
return ret;
}
/*获取用户名 */
char *uname = cJSON_GetObjectItem(cjson , "username")->valuestring;
printf("username :%s\n", uname);
/*判断username长度是否正确*/
if( strlen(uname) > USERNAME_MAXLEN )
{
cJSON_Delete(cjson);
ret = RET_IPINVALID;
return ret;
}
/*获取密码 */
char *upwd = cJSON_GetObjectItem(cjson, "password")->valuestring;
printf("password :%s\n", upwd);
/*判断password长度是否正确 */
if( strlen(upwd) > PASSWORD_MAXLEN )
{
cJSON_Delete(cjson);
ret = RET_IPINVALID;
return ret;
}
/*调用认证接口函数 */
user_auth_login(uname, upwd, resultinfo);
printf("认证结束\n");
/*认证成功 */
if (resultinfo->ret == 0)
{
printf("认证成功\n");
uint32_t client_ip=10001; /*解析报文拿到用户IP */
printf("client_ip :%d\n", client_ip);
Init_hash(); /*初始化hash表放在配置恢复处 */
/*重定向到认证成功界面-调用web server提供的接口发送url地址给接口实现重定向 */
/*客户端访问认证成功界面方法:GET */
char method[10] = {"GET"};
/*如果method是GET,判断这个用户是否认证过*/
if(0 == strncmp(method, "GET",10))
{
struct user_info * uinfo;
uinfo = (struct user_info *)malloc(sizeof(struct user_info));
if (NULL == uinfo)
{
cJSON_Delete(cjson);
ret = RET_NOMEM;
return ret;
}
/*用户认证过则跳出语句,不访问认证成功界面 */
uinfo = ufind_user(client_ip);
if ( NULL != uinfo )
{
printf("用户已经认证过\n");
free(uinfo);
cJSON_Delete(cjson);
ret = RET_ERR;
return ret ;
}
uadd_user(client_ip,resultinfo->user_id);
uprintf_users();
uresult->resultcode = resultinfo->ret;
uresult->remain_lock_time = time;
uresult->message = mes[resultinfo->ret];
printf("resultcode:%d remain_lock_time:%d message:%s\n",uresult->resultcode,
uresult->remain_lock_time, uresult->message );
free(uinfo);
cJSON_Delete(cjson);
return ret;
}
}
/*认证锁定*/
if (resultinfo->ret == 4)
{
time = resultinfo->remain_lock_time;
uresult->resultcode = resultinfo->ret;
uresult->remain_lock_time = time;
uresult->message = mes[resultinfo->ret];
printf("resultcode:%d remain_lock_time:%d message:%s\n",uresult->resultcode,
uresult->remain_lock_time, uresult->message );
cJSON_Delete(cjson);
ret = RET_ERR;
return ret;
}
/*认证失败*/
if ( (resultinfo->ret != 4) && (resultinfo->ret != 0))
{
printf("the value of resultcode is %d\n", resultinfo->ret);
uresult->resultcode = resultinfo->ret;
uresult->remain_lock_time = time;
uresult->message = mes[resultinfo->ret];
printf("resultcode:%d remain_lock_time:%d message:%s\n",uresult->resultcode,
uresult->remain_lock_time, uresult->message );
cJSON_Delete(cjson);
ret = RET_ERR;
return ret;
}
cJSON_Delete(cjson);
return ret;
}

View File

@ -0,0 +1,22 @@
#ifndef USERAUTH_H_
#define USERAUTH_H_
#define USERNAME_MAXLEN 65
#define PASSWORD_MAXLEN 25
#include <time.h>
#include "../../Product/common/user_auth.h"
#include "../../Platform/common/rpc/rpc_common.h"
typedef void* pointer;
/*输出函数结构体 */
typedef struct result{
auth_ret resultcode;
char *message; /*返回描述用指针表示数组 */
time_t remain_lock_time; /*锁定剩余时间 */
}RESULT;
ret_code user_auth(pointer content, RESULT *uresult);
#endif