You are viewing a plain text version of this content. The canonical link for it is here.
Posted to common-commits@hadoop.apache.org by ji...@apache.org on 2015/10/08 23:17:12 UTC
[01/35] hadoop git commit: YARN-4209. RMStateStore FENCED state doesn’t work due to updateFencedState called by stateMachine.doTransition. (Zhihai Xu via rohithsharmaks)
Repository: hadoop
Updated Branches:
refs/heads/HDFS-8966 cc0ca64d4 -> b645d67a9 (forced update)
YARN-4209. RMStateStore FENCED state doesn’t work due to updateFencedState called by stateMachine.doTransition. (Zhihai Xu via rohithsharmaks)
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/9156fc60
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/9156fc60
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/9156fc60
Branch: refs/heads/HDFS-8966
Commit: 9156fc60c654e9305411686878acb443f3be1e67
Parents: 1bca1bb
Author: Rohith Sharma K S <ro...@apache.org>
Authored: Wed Oct 7 09:34:59 2015 +0530
Committer: Rohith Sharma K S <ro...@apache.org>
Committed: Wed Oct 7 09:34:59 2015 +0530
----------------------------------------------------------------------
hadoop-yarn-project/CHANGES.txt | 3 +
.../resourcemanager/recovery/RMStateStore.java | 261 +++++++++++++------
.../recovery/TestMemoryRMStateStore.java | 65 +++++
3 files changed, 243 insertions(+), 86 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/9156fc60/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 9d12b82..de81879 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -1020,6 +1020,9 @@ Release 2.7.2 - UNRELEASED
YARN-3619. ContainerMetrics unregisters during getMetrics and leads to
ConcurrentModificationException (Zhihai Xu via jlowe)
+ YARN-4209. RMStateStore FENCED state doesn’t work due to updateFencedState called
+ by stateMachine.doTransition. (Zhihai Xu via rohithsharmaks)
+
Release 2.7.1 - 2015-07-06
INCOMPATIBLE CHANGES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/9156fc60/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java
index aa5caf9..a2cf517 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java
@@ -67,7 +67,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType;
import org.apache.hadoop.yarn.state.InvalidStateTransitionException;
-import org.apache.hadoop.yarn.state.SingleArcTransition;
+import org.apache.hadoop.yarn.state.MultipleArcTransition;
import org.apache.hadoop.yarn.state.StateMachine;
import org.apache.hadoop.yarn.state.StateMachineFactory;
@@ -100,7 +100,10 @@ public abstract class RMStateStore extends AbstractService {
public static final Log LOG = LogFactory.getLog(RMStateStore.class);
- private enum RMStateStoreState {
+ /**
+ * The enum defines state of RMStateStore.
+ */
+ public enum RMStateStoreState {
ACTIVE,
FENCED
};
@@ -114,41 +117,57 @@ public abstract class RMStateStore extends AbstractService {
RMStateStoreEventType,
RMStateStoreEvent>(
RMStateStoreState.ACTIVE)
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.STORE_APP, new StoreAppTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
- RMStateStoreEventType.UPDATE_APP, new UpdateAppTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
+ RMStateStoreEventType.UPDATE_APP, new UpdateAppTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.REMOVE_APP, new RemoveAppTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
- RMStateStoreEventType.STORE_APP_ATTEMPT, new StoreAppAttemptTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
- RMStateStoreEventType.UPDATE_APP_ATTEMPT, new UpdateAppAttemptTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
+ RMStateStoreEventType.STORE_APP_ATTEMPT,
+ new StoreAppAttemptTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
+ RMStateStoreEventType.UPDATE_APP_ATTEMPT,
+ new UpdateAppAttemptTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.STORE_MASTERKEY,
- new StoreRMDTMasterKeyTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ new StoreRMDTMasterKeyTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.REMOVE_MASTERKEY,
- new RemoveRMDTMasterKeyTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ new RemoveRMDTMasterKeyTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.STORE_DELEGATION_TOKEN,
- new StoreRMDTTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ new StoreRMDTTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.REMOVE_DELEGATION_TOKEN,
- new RemoveRMDTTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ new RemoveRMDTTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.UPDATE_DELEGATION_TOKEN,
- new UpdateRMDTTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
- RMStateStoreEventType.UPDATE_AMRM_TOKEN,
- new StoreOrUpdateAMRMTokenTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ new UpdateRMDTTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
+ RMStateStoreEventType.UPDATE_AMRM_TOKEN,
+ new StoreOrUpdateAMRMTokenTransition())
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.STORE_RESERVATION,
new StoreReservationAllocationTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.UPDATE_RESERVATION,
new UpdateReservationAllocationTransition())
- .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE,
+ .addTransition(RMStateStoreState.ACTIVE,
+ EnumSet.of(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED),
RMStateStoreEventType.REMOVE_RESERVATION,
new RemoveReservationAllocationTransition())
.addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED,
@@ -176,14 +195,17 @@ public abstract class RMStateStore extends AbstractService {
RMStateStoreEvent> stateMachine;
private static class StoreAppTransition
- implements SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ implements MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreAppEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
ApplicationStateData appState =
((RMStateStoreAppEvent) event).getAppState();
ApplicationId appId =
@@ -195,20 +217,24 @@ public abstract class RMStateStore extends AbstractService {
RMAppEventType.APP_NEW_SAVED));
} catch (Exception e) {
LOG.error("Error storing app: " + appId, e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
};
}
private static class UpdateAppTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateUpdateAppEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
ApplicationStateData appState =
((RMStateUpdateAppEvent) event).getAppState();
ApplicationId appId =
@@ -222,20 +248,24 @@ public abstract class RMStateStore extends AbstractService {
}
} catch (Exception e) {
LOG.error("Error updating app: " + appId, e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
};
}
private static class RemoveAppTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreRemoveAppEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
ApplicationStateData appState =
((RMStateStoreRemoveAppEvent) event).getAppState();
ApplicationId appId =
@@ -245,20 +275,24 @@ public abstract class RMStateStore extends AbstractService {
store.removeApplicationStateInternal(appState);
} catch (Exception e) {
LOG.error("Error removing app: " + appId, e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
};
}
private static class StoreAppAttemptTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreAppAttemptEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
ApplicationAttemptStateData attemptState =
((RMStateStoreAppAttemptEvent) event).getAppAttemptState();
try {
@@ -272,20 +306,24 @@ public abstract class RMStateStore extends AbstractService {
RMAppAttemptEventType.ATTEMPT_NEW_SAVED));
} catch (Exception e) {
LOG.error("Error storing appAttempt: " + attemptState.getAttemptId(), e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
};
}
private static class UpdateAppAttemptTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateUpdateAppAttemptEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
ApplicationAttemptStateData attemptState =
((RMStateUpdateAppAttemptEvent) event).getAppAttemptState();
try {
@@ -299,20 +337,24 @@ public abstract class RMStateStore extends AbstractService {
RMAppAttemptEventType.ATTEMPT_UPDATE_SAVED));
} catch (Exception e) {
LOG.error("Error updating appAttempt: " + attemptState.getAttemptId(), e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
};
}
private static class StoreRMDTTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreRMDTEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
RMStateStoreRMDTEvent dtEvent = (RMStateStoreRMDTEvent) event;
try {
LOG.info("Storing RMDelegationToken and SequenceNumber");
@@ -321,20 +363,24 @@ public abstract class RMStateStore extends AbstractService {
} catch (Exception e) {
LOG.error("Error While Storing RMDelegationToken and SequenceNumber ",
e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
private static class RemoveRMDTTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreRMDTEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
RMStateStoreRMDTEvent dtEvent = (RMStateStoreRMDTEvent) event;
try {
LOG.info("Removing RMDelegationToken and SequenceNumber");
@@ -342,21 +388,24 @@ public abstract class RMStateStore extends AbstractService {
} catch (Exception e) {
LOG.error("Error While Removing RMDelegationToken and SequenceNumber ",
e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
private static class UpdateRMDTTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreRMDTEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
-
+ boolean isFenced = false;
RMStateStoreRMDTEvent dtEvent = (RMStateStoreRMDTEvent) event;
try {
LOG.info("Updating RMDelegationToken and SequenceNumber");
@@ -365,20 +414,24 @@ public abstract class RMStateStore extends AbstractService {
} catch (Exception e) {
LOG.error("Error While Updating RMDelegationToken and SequenceNumber ",
e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
private static class StoreRMDTMasterKeyTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreRMDTMasterKeyEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
RMStateStoreRMDTMasterKeyEvent dtEvent =
(RMStateStoreRMDTMasterKeyEvent) event;
try {
@@ -386,20 +439,24 @@ public abstract class RMStateStore extends AbstractService {
store.storeRMDTMasterKeyState(dtEvent.getDelegationKey());
} catch (Exception e) {
LOG.error("Error While Storing RMDTMasterKey.", e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
private static class RemoveRMDTMasterKeyTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreRMDTMasterKeyEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
RMStateStoreRMDTMasterKeyEvent dtEvent =
(RMStateStoreRMDTMasterKeyEvent) event;
try {
@@ -407,42 +464,49 @@ public abstract class RMStateStore extends AbstractService {
store.removeRMDTMasterKeyState(dtEvent.getDelegationKey());
} catch (Exception e) {
LOG.error("Error While Removing RMDTMasterKey.", e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
private static class StoreOrUpdateAMRMTokenTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreAMRMTokenEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
RMStateStoreAMRMTokenEvent amrmEvent = (RMStateStoreAMRMTokenEvent) event;
-
+ boolean isFenced = false;
try {
LOG.info("Updating AMRMToken");
store.storeOrUpdateAMRMTokenSecretManagerState(
amrmEvent.getAmrmTokenSecretManagerState(), amrmEvent.isUpdate());
} catch (Exception e) {
LOG.error("Error storing info for AMRMTokenSecretManager", e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
private static class StoreReservationAllocationTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreStoreReservationEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
RMStateStoreStoreReservationEvent reservationEvent =
(RMStateStoreStoreReservationEvent) event;
try {
@@ -454,20 +518,24 @@ public abstract class RMStateStore extends AbstractService {
reservationEvent.getReservationIdName());
} catch (Exception e) {
LOG.error("Error while storing reservation allocation.", e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
private static class UpdateReservationAllocationTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreStoreReservationEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
RMStateStoreStoreReservationEvent reservationEvent =
(RMStateStoreStoreReservationEvent) event;
try {
@@ -479,20 +547,24 @@ public abstract class RMStateStore extends AbstractService {
reservationEvent.getReservationIdName());
} catch (Exception e) {
LOG.error("Error while updating reservation allocation.", e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
private static class RemoveReservationAllocationTransition implements
- SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ MultipleArcTransition<RMStateStore, RMStateStoreEvent,
+ RMStateStoreState> {
@Override
- public void transition(RMStateStore store, RMStateStoreEvent event) {
+ public RMStateStoreState transition(RMStateStore store,
+ RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreStoreReservationEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
- return;
+ return RMStateStoreState.ACTIVE;
}
+ boolean isFenced = false;
RMStateStoreStoreReservationEvent reservationEvent =
(RMStateStoreStoreReservationEvent) event;
try {
@@ -503,11 +575,16 @@ public abstract class RMStateStore extends AbstractService {
reservationEvent.getReservationIdName());
} catch (Exception e) {
LOG.error("Error while removing reservation allocation.", e);
- store.notifyStoreOperationFailed(e);
+ isFenced = store.notifyStoreOperationFailedInternal(e);
}
+ return finalState(isFenced);
}
}
+ private static RMStateStoreState finalState(boolean isFenced) {
+ return isFenced ? RMStateStoreState.FENCED : RMStateStoreState.ACTIVE;
+ }
+
public RMStateStore() {
super(RMStateStore.class.getName());
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
@@ -1006,17 +1083,28 @@ public abstract class RMStateStore extends AbstractService {
}
}
- @SuppressWarnings("unchecked")
/**
* This method is called to notify the ResourceManager that the store
* operation has failed.
* @param failureCause the exception due to which the operation failed
*/
protected void notifyStoreOperationFailed(Exception failureCause) {
+ if (isFencedState()) {
+ return;
+ }
+ if (notifyStoreOperationFailedInternal(failureCause)) {
+ updateFencedState();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private boolean notifyStoreOperationFailedInternal(
+ Exception failureCause) {
+ boolean isFenced = false;
LOG.error("State store operation failed ", failureCause);
if (HAUtil.isHAEnabled(getConfig())) {
LOG.warn("State-store fenced ! Transitioning RM to standby");
- updateFencedState();
+ isFenced = true;
Thread standByTransitionThread =
new Thread(new StandByTransitionThread());
standByTransitionThread.setName("StandByTransitionThread Handler");
@@ -1029,6 +1117,7 @@ public abstract class RMStateStore extends AbstractService {
} else {
LOG.warn("Skip the state-store error.");
}
+ return isFenced;
}
@SuppressWarnings("unchecked")
http://git-wip-us.apache.org/repos/asf/hadoop/blob/9156fc60/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestMemoryRMStateStore.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestMemoryRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestMemoryRMStateStore.java
new file mode 100644
index 0000000..89b9e2b
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestMemoryRMStateStore.java
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+package org.apache.hadoop.yarn.server.resourcemanager.recovery;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
+import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+
+public class TestMemoryRMStateStore {
+
+ @Test
+ public void testNotifyStoreOperationFailed() throws Exception {
+ RMStateStore store = new MemoryRMStateStore() {
+ @Override
+ public synchronized void removeRMDelegationTokenState(
+ RMDelegationTokenIdentifier rmDTIdentifier) throws Exception {
+ throw new Exception("testNotifyStoreOperationFailed");
+ }
+ };
+ Configuration conf = new Configuration();
+ conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, true);
+ store.init(conf);
+ ResourceManager mockRM = mock(ResourceManager.class);
+ store.setResourceManager(mockRM);
+ RMDelegationTokenIdentifier mockTokenId =
+ mock(RMDelegationTokenIdentifier.class);
+ store.removeRMDelegationToken(mockTokenId);
+ assertTrue("RMStateStore should have been in fenced state",
+ store.isFencedState());
+ store = new MemoryRMStateStore() {
+ @Override
+ public synchronized void removeRMDelegationToken(
+ RMDelegationTokenIdentifier rmDTIdentifier) {
+ notifyStoreOperationFailed(new Exception(
+ "testNotifyStoreOperationFailed"));
+ }
+ };
+ store.init(conf);
+ store.setResourceManager(mockRM);
+ store.removeRMDelegationToken(mockTokenId);
+ assertTrue("RMStateStore should have been in fenced state",
+ store.isFencedState());
+ }
+}
[21/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_chmod.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_chmod.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_chmod.c
new file mode 100644
index 0000000..8c25f53
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_chmod.c
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_users.h"
+#include "fuse_connect.h"
+
+int dfs_chmod(const char *path, mode_t mode)
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ TRACE1("chmod", path)
+ int ret = 0;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+
+ if (hdfsChmod(fs, path, (short)mode)) {
+ ERROR("Could not chmod %s to %d", path, (int)mode);
+ ret = (errno > 0) ? -errno : -EIO;
+ goto cleanup;
+ }
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_chown.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_chown.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_chown.c
new file mode 100644
index 0000000..2a6b61c
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_chown.c
@@ -0,0 +1,87 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_users.h"
+#include "fuse_impls.h"
+#include "fuse_connect.h"
+
+#include <stdlib.h>
+
+int dfs_chown(const char *path, uid_t uid, gid_t gid)
+{
+ struct hdfsConn *conn = NULL;
+ int ret = 0;
+ char *user = NULL;
+ char *group = NULL;
+
+ TRACE1("chown", path)
+
+ // retrieve dfs specific data
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ // check params and the context var
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+
+ if ((uid == -1) && (gid == -1)) {
+ ret = 0;
+ goto cleanup;
+ }
+ if (uid != -1) {
+ user = getUsername(uid);
+ if (NULL == user) {
+ ERROR("Could not lookup the user id string %d",(int)uid);
+ ret = -EIO;
+ goto cleanup;
+ }
+ }
+ if (gid != -1) {
+ group = getGroup(gid);
+ if (group == NULL) {
+ ERROR("Could not lookup the group id string %d",(int)gid);
+ ret = -EIO;
+ goto cleanup;
+ }
+ }
+
+ ret = fuseConnect(user, fuse_get_context(), &conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnect: failed to open a libhdfs connection! "
+ "error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+
+ if (hdfsChown(hdfsConnGetFs(conn), path, user, group)) {
+ ret = errno;
+ ERROR("Could not chown %s to %d:%d: error %d", path, (int)uid, gid, ret);
+ ret = (ret > 0) ? -ret : -EIO;
+ goto cleanup;
+ }
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ free(user);
+ free(group);
+
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_create.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_create.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_create.c
new file mode 100644
index 0000000..256e383
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_create.c
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+
+int dfs_create(const char *path, mode_t mode, struct fuse_file_info *fi)
+{
+ TRACE1("create", path)
+ fi->flags |= mode;
+ return dfs_open(path, fi);
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_flush.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_flush.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_flush.c
new file mode 100644
index 0000000..adb065b
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_flush.c
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_connect.h"
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_file_handle.h"
+
+int dfs_flush(const char *path, struct fuse_file_info *fi) {
+ TRACE1("flush", path)
+
+ // retrieve dfs specific data
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ // check params and the context var
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+ assert(fi);
+
+ if (NULL == (void*)fi->fh) {
+ return 0;
+ }
+
+ // note that fuse calls flush on RO files too and hdfs does not like that and will return an error
+ if (fi->flags & O_WRONLY) {
+
+ dfs_fh *fh = (dfs_fh*)fi->fh;
+ assert(fh);
+ hdfsFile file_handle = (hdfsFile)fh->hdfsFH;
+ assert(file_handle);
+ if (hdfsFlush(hdfsConnGetFs(fh->conn), file_handle) != 0) {
+ ERROR("Could not flush %lx for %s\n",(long)file_handle, path);
+ return -EIO;
+ }
+ }
+
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_getattr.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_getattr.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_getattr.c
new file mode 100644
index 0000000..2e43518
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_getattr.c
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_stat_struct.h"
+#include "fuse_connect.h"
+
+int dfs_getattr(const char *path, struct stat *st)
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ int ret;
+ hdfsFileInfo *info;
+
+ TRACE1("getattr", path)
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+ assert(dfs);
+ assert(path);
+ assert(st);
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+
+ info = hdfsGetPathInfo(fs,path);
+ if (NULL == info) {
+ ret = -ENOENT;
+ goto cleanup;
+ }
+ fill_stat_structure(&info[0], st);
+
+ // setup hard link info - for a file it is 1 else num entries in a dir + 2 (for . and ..)
+ if (info[0].mKind == kObjectKindDirectory) {
+ int numEntries = 0;
+ hdfsFileInfo *info = hdfsListDirectory(fs,path,&numEntries);
+
+ if (info) {
+ hdfsFreeFileInfo(info,numEntries);
+ }
+ st->st_nlink = numEntries + 2;
+ } else {
+ // not a directory
+ st->st_nlink = 1;
+ }
+
+ // free the info pointer
+ hdfsFreeFileInfo(info,1);
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_mkdir.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_mkdir.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_mkdir.c
new file mode 100644
index 0000000..b05551f
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_mkdir.c
@@ -0,0 +1,70 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_trash.h"
+#include "fuse_connect.h"
+
+int dfs_mkdir(const char *path, mode_t mode)
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+ int ret;
+
+ TRACE1("mkdir", path)
+
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+
+ if (is_protected(path)) {
+ ERROR("HDFS trying to create directory %s", path);
+ return -EACCES;
+ }
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+
+ // In theory the create and chmod should be atomic.
+
+ if (hdfsCreateDirectory(fs, path)) {
+ ERROR("HDFS could not create directory %s", path);
+ ret = (errno > 0) ? -errno : -EIO;
+ goto cleanup;
+ }
+
+ if (hdfsChmod(fs, path, (short)mode)) {
+ ERROR("Could not chmod %s to %d", path, (int)mode);
+ ret = (errno > 0) ? -errno : -EIO;
+ }
+ ret = 0;
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_mknod.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_mknod.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_mknod.c
new file mode 100644
index 0000000..c745cf1
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_mknod.c
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+
+int dfs_mknod(const char *path, mode_t mode, dev_t rdev)
+{
+ TRACE1("mknod", path);
+ DEBUG("dfs_mknod");
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_open.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_open.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_open.c
new file mode 100644
index 0000000..ca670ce
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_open.c
@@ -0,0 +1,172 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_connect.h"
+#include "fuse_file_handle.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+/**
+ * Given a set of FUSE flags, determine the libhdfs flags we need.
+ *
+ * This is complicated by two things:
+ * 1. libhdfs doesn't support O_RDWR at all;
+ * 2. when given O_WRONLY, libhdfs will truncate the file unless O_APPEND is
+ * also given. In other words, there is an implicit O_TRUNC.
+ *
+ * Probably the next iteration of the libhdfs interface should not use the POSIX
+ * flags at all, since, as you can see, they don't really match up very closely
+ * to the POSIX meaning. However, for the time being, this is the API.
+ *
+ * @param fs The libhdfs object
+ * @param path The path we're opening
+ * @param flags The FUSE flags
+ *
+ * @return negative error code on failure; flags otherwise.
+ */
+static int64_t get_hdfs_open_flags(hdfsFS fs, const char *path, int flags)
+{
+ int64_t ret;
+ hdfsFileInfo *info;
+
+ if ((flags & O_ACCMODE) == O_RDONLY) {
+ return O_RDONLY;
+ }
+ if (flags & O_TRUNC) {
+ /* If we're opening for write or read/write, O_TRUNC means we should blow
+ * away the file which is there and create our own file.
+ * */
+ return O_WRONLY;
+ }
+ info = hdfsGetPathInfo(fs, path);
+ if (info) {
+ if (info->mSize == 0) {
+ // If the file has zero length, we shouldn't feel bad about blowing it
+ // away.
+ ret = O_WRONLY;
+ } else if ((flags & O_ACCMODE) == O_RDWR) {
+ // HACK: translate O_RDWR requests into O_RDONLY if the file already
+ // exists and has non-zero length.
+ ret = O_RDONLY;
+ } else { // O_WRONLY
+ // HACK: translate O_WRONLY requests into append if the file already
+ // exists.
+ ret = O_WRONLY | O_APPEND;
+ }
+ } else { // !info
+ if (flags & O_CREAT) {
+ ret = O_WRONLY;
+ } else {
+ ret = -ENOENT;
+ }
+ }
+ if (info) {
+ hdfsFreeFileInfo(info, 1);
+ }
+ return ret;
+}
+
+int dfs_open(const char *path, struct fuse_file_info *fi)
+{
+ hdfsFS fs = NULL;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+ dfs_fh *fh = NULL;
+ int mutexInit = 0, ret, flags = 0;
+ int64_t flagRet;
+
+ TRACE1("open", path)
+
+ // check params and the context var
+ assert(path);
+ assert('/' == *path);
+ assert(dfs);
+
+ // retrieve dfs specific data
+ fh = (dfs_fh*)calloc(1, sizeof (dfs_fh));
+ if (!fh) {
+ ERROR("Malloc of new file handle failed");
+ ret = -EIO;
+ goto error;
+ }
+ ret = fuseConnectAsThreadUid(&fh->conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto error;
+ }
+ fs = hdfsConnGetFs(fh->conn);
+ flagRet = get_hdfs_open_flags(fs, path, fi->flags);
+ if (flagRet < 0) {
+ ret = -flagRet;
+ goto error;
+ }
+ flags = flagRet;
+ if ((fh->hdfsFH = hdfsOpenFile(fs, path, flags, 0, 0, 0)) == NULL) {
+ ERROR("Could not open file %s (errno=%d)", path, errno);
+ if (errno == 0 || errno == EINTERNAL) {
+ ret = -EIO;
+ goto error;
+ }
+ ret = -errno;
+ goto error;
+ }
+
+ ret = pthread_mutex_init(&fh->mutex, NULL);
+ if (ret) {
+ fprintf(stderr, "dfs_open: error initializing mutex: error %d\n", ret);
+ ret = -EIO;
+ goto error;
+ }
+ mutexInit = 1;
+
+ if ((flags & O_ACCMODE) == O_WRONLY) {
+ fh->buf = NULL;
+ } else {
+ assert(dfs->rdbuffer_size > 0);
+ fh->buf = (char*)malloc(dfs->rdbuffer_size * sizeof(char));
+ if (NULL == fh->buf) {
+ ERROR("Could not allocate memory for a read for file %s\n", path);
+ ret = -EIO;
+ goto error;
+ }
+ fh->buffersStartOffset = 0;
+ fh->bufferSize = 0;
+ }
+ fi->fh = (uint64_t)fh;
+ return 0;
+
+error:
+ if (fh) {
+ if (mutexInit) {
+ pthread_mutex_destroy(&fh->mutex);
+ }
+ free(fh->buf);
+ if (fh->hdfsFH) {
+ hdfsCloseFile(fs, fh->hdfsFH);
+ }
+ if (fh->conn) {
+ hdfsConnRelease(fh->conn);
+ }
+ free(fh);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_read.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_read.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_read.c
new file mode 100644
index 0000000..feade45
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_read.c
@@ -0,0 +1,163 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_connect.h"
+#include "fuse_dfs.h"
+#include "fuse_file_handle.h"
+#include "fuse_impls.h"
+
+static size_t min(const size_t x, const size_t y) {
+ return x < y ? x : y;
+}
+
+/**
+ * dfs_read
+ *
+ * Reads from dfs or the open file's buffer. Note that fuse requires that
+ * either the entire read be satisfied or the EOF is hit or direct_io is enabled
+ *
+ */
+int dfs_read(const char *path, char *buf, size_t size, off_t offset,
+ struct fuse_file_info *fi)
+{
+ TRACE1("read",path)
+
+ // retrieve dfs specific data
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ // check params and the context var
+ assert(dfs);
+ assert(path);
+ assert(buf);
+ assert(offset >= 0);
+ assert(size >= 0);
+ assert(fi);
+
+ dfs_fh *fh = (dfs_fh*)fi->fh;
+ hdfsFS fs = hdfsConnGetFs(fh->conn);
+
+ assert(fh != NULL);
+ assert(fh->hdfsFH != NULL);
+
+ // special case this as simplifies the rest of the logic to know the caller wanted > 0 bytes
+ if (size == 0)
+ return 0;
+
+ // If size is bigger than the read buffer, then just read right into the user supplied buffer
+ if ( size >= dfs->rdbuffer_size) {
+ int num_read;
+ size_t total_read = 0;
+ while (size - total_read > 0 && (num_read = hdfsPread(fs, fh->hdfsFH, offset + total_read, buf + total_read, size - total_read)) > 0) {
+ total_read += num_read;
+ }
+ // if there was an error before satisfying the current read, this logic declares it an error
+ // and does not try to return any of the bytes read. Don't think it matters, so the code
+ // is just being conservative.
+ if (total_read < size && num_read < 0) {
+ total_read = -EIO;
+ }
+ return total_read;
+ }
+
+ //
+ // Critical section - protect from multiple reads in different threads accessing the read buffer
+ // (no returns until end)
+ //
+
+ pthread_mutex_lock(&fh->mutex);
+
+ // used only to check the postcondition of this function - namely that we satisfy
+ // the entire read or EOF is hit.
+ int isEOF = 0;
+ int ret = 0;
+
+ // check if the buffer is empty or
+ // the read starts before the buffer starts or
+ // the read ends after the buffer ends
+
+ if (fh->bufferSize == 0 ||
+ offset < fh->buffersStartOffset ||
+ offset + size > fh->buffersStartOffset + fh->bufferSize)
+ {
+ // Read into the buffer from DFS
+ int num_read = 0;
+ size_t total_read = 0;
+
+ while (dfs->rdbuffer_size - total_read > 0 &&
+ (num_read = hdfsPread(fs, fh->hdfsFH, offset + total_read, fh->buf + total_read, dfs->rdbuffer_size - total_read)) > 0) {
+ total_read += num_read;
+ }
+
+ // if there was an error before satisfying the current read, this logic declares it an error
+ // and does not try to return any of the bytes read. Don't think it matters, so the code
+ // is just being conservative.
+ if (total_read < size && num_read < 0) {
+ // invalidate the buffer
+ fh->bufferSize = 0;
+ ERROR("pread failed for %s with return code %d", path, (int)num_read);
+ ret = -EIO;
+ } else {
+ // Either EOF, all read or read beyond size, but then there was an error
+ fh->bufferSize = total_read;
+ fh->buffersStartOffset = offset;
+
+ if (dfs->rdbuffer_size - total_read > 0) {
+ // assert(num_read == 0); this should be true since if num_read < 0 handled above.
+ isEOF = 1;
+ }
+ }
+ }
+
+ //
+ // NOTE on EOF, fh->bufferSize == 0 and ret = 0 ,so the logic for copying data into the caller's buffer is bypassed, and
+ // the code returns 0 as required
+ //
+ if (ret == 0 && fh->bufferSize > 0) {
+
+ assert(offset >= fh->buffersStartOffset);
+ assert(fh->buf);
+
+ const size_t bufferReadIndex = offset - fh->buffersStartOffset;
+ assert(bufferReadIndex >= 0 && bufferReadIndex < fh->bufferSize);
+
+ const size_t amount = min(fh->buffersStartOffset + fh->bufferSize - offset, size);
+ assert(amount >= 0 && amount <= fh->bufferSize);
+
+ const char *offsetPtr = fh->buf + bufferReadIndex;
+ assert(offsetPtr >= fh->buf);
+ assert(offsetPtr + amount <= fh->buf + fh->bufferSize);
+
+ memcpy(buf, offsetPtr, amount);
+
+ ret = amount;
+ }
+
+ //
+ // Critical section end
+ //
+ pthread_mutex_unlock(&fh->mutex);
+
+ // fuse requires the below and the code should guarantee this assertion
+ // 3 cases on return:
+ // 1. entire read satisfied
+ // 2. partial read and isEOF - including 0 size read
+ // 3. error
+ assert(ret == size || isEOF || ret < 0);
+
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_readdir.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_readdir.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_readdir.c
new file mode 100644
index 0000000..326f573
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_readdir.c
@@ -0,0 +1,122 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_stat_struct.h"
+#include "fuse_connect.h"
+
+int dfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
+ off_t offset, struct fuse_file_info *fi)
+{
+ int ret;
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ TRACE1("readdir", path)
+
+ assert(dfs);
+ assert(path);
+ assert(buf);
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+
+ // Read dirents. Calling a variant that just returns the final path
+ // component (HDFS-975) would save us from parsing it out below.
+ int numEntries = 0;
+ hdfsFileInfo *info = hdfsListDirectory(fs, path, &numEntries);
+
+ // NULL means either the directory doesn't exist or maybe IO error.
+ if (NULL == info) {
+ ret = (errno > 0) ? -errno : -ENOENT;
+ goto cleanup;
+ }
+
+ int i ;
+ for (i = 0; i < numEntries; i++) {
+ if (NULL == info[i].mName) {
+ ERROR("Path %s info[%d].mName is NULL", path, i);
+ continue;
+ }
+
+ struct stat st;
+ fill_stat_structure(&info[i], &st);
+
+ // Find the final path component
+ const char *str = strrchr(info[i].mName, '/');
+ if (NULL == str) {
+ ERROR("Invalid URI %s", info[i].mName);
+ continue;
+ }
+ str++;
+
+ // pack this entry into the fuse buffer
+ int res = 0;
+ if ((res = filler(buf,str,&st,0)) != 0) {
+ ERROR("Readdir filler failed: %d\n",res);
+ }
+ }
+
+ // insert '.' and '..'
+ const char *const dots [] = { ".",".."};
+ for (i = 0 ; i < 2 ; i++)
+ {
+ struct stat st;
+ memset(&st, 0, sizeof(struct stat));
+
+ // set to 0 to indicate not supported for directory because we cannot (efficiently) get this info for every subdirectory
+ st.st_nlink = 0;
+
+ // setup stat size and acl meta data
+ st.st_size = 512;
+ st.st_blksize = 512;
+ st.st_blocks = 1;
+ st.st_mode = (S_IFDIR | 0777);
+ st.st_uid = default_id;
+ st.st_gid = default_id;
+ // todo fix below times
+ st.st_atime = 0;
+ st.st_mtime = 0;
+ st.st_ctime = 0;
+
+ const char *const str = dots[i];
+
+ // flatten the info using fuse's function into a buffer
+ int res = 0;
+ if ((res = filler(buf,str,&st,0)) != 0) {
+ ERROR("Readdir filler failed: %d\n",res);
+ }
+ }
+ // free the info pointers
+ hdfsFreeFileInfo(info,numEntries);
+ ret = 0;
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_release.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_release.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_release.c
new file mode 100644
index 0000000..0316de6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_release.c
@@ -0,0 +1,66 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_file_handle.h"
+#include "fuse_connect.h"
+
+#include <stdlib.h>
+
+/**
+ * release a fuse_file_info structure.
+ *
+ * When this function is invoked, there are no more references to our
+ * fuse_file_info structure that exist anywhere. So there is no need for
+ * locking to protect this structure here.
+ *
+ * Another thread could open() the same file, and get a separate, different file
+ * descriptor with a different, separate fuse_file_info structure. In HDFS,
+ * this results in one writer winning and overwriting everything the other
+ * writer has done.
+ */
+
+int dfs_release (const char *path, struct fuse_file_info *fi) {
+ TRACE1("release", path)
+
+ // retrieve dfs specific data
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ // check params and the context var
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+
+ int ret = 0;
+ dfs_fh *fh = (dfs_fh*)fi->fh;
+ assert(fh);
+ hdfsFile file_handle = (hdfsFile)fh->hdfsFH;
+ if (NULL != file_handle) {
+ if (hdfsCloseFile(hdfsConnGetFs(fh->conn), file_handle) != 0) {
+ ERROR("Could not close handle %ld for %s\n",(long)file_handle, path);
+ ret = -EIO;
+ }
+ }
+ free(fh->buf);
+ hdfsConnRelease(fh->conn);
+ pthread_mutex_destroy(&fh->mutex);
+ free(fh);
+ fi->fh = 0;
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_rename.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_rename.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_rename.c
new file mode 100644
index 0000000..ad7c7e5
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_rename.c
@@ -0,0 +1,66 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_trash.h"
+#include "fuse_connect.h"
+
+int dfs_rename(const char *from, const char *to)
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+ int ret;
+
+ TRACE1("rename", from)
+
+ // check params and the context var
+ assert(from);
+ assert(to);
+ assert(dfs);
+
+ assert('/' == *from);
+ assert('/' == *to);
+
+ if (is_protected(from) || is_protected(to)) {
+ ERROR("Could not rename %s to %s", from, to);
+ return -EACCES;
+ }
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+ if (hdfsRename(fs, from, to)) {
+ ERROR("Rename %s to %s failed", from, to);
+ ret = (errno > 0) ? -errno : -EIO;
+ goto cleanup;
+ }
+ ret = 0;
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_rmdir.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_rmdir.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_rmdir.c
new file mode 100644
index 0000000..493807f
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_rmdir.c
@@ -0,0 +1,76 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_trash.h"
+#include "fuse_connect.h"
+
+extern const char *const TrashPrefixDir;
+
+int dfs_rmdir(const char *path)
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ int ret;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+ int numEntries = 0;
+ hdfsFileInfo *info = NULL;
+
+ TRACE1("rmdir", path)
+
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+
+ if (is_protected(path)) {
+ ERROR("Trying to delete protected directory %s", path);
+ ret = -EACCES;
+ goto cleanup;
+ }
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+ info = hdfsListDirectory(fs, path, &numEntries);
+ if (numEntries) {
+ ret = -ENOTEMPTY;
+ goto cleanup;
+ }
+
+ if (hdfsDeleteWithTrash(fs, path, dfs->usetrash)) {
+ ERROR("Error trying to delete directory %s", path);
+ ret = -EIO;
+ goto cleanup;
+ }
+ ret = 0;
+
+cleanup:
+ if (info) {
+ hdfsFreeFileInfo(info, numEntries);
+ }
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_statfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_statfs.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_statfs.c
new file mode 100644
index 0000000..c9306a2
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_statfs.c
@@ -0,0 +1,70 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_connect.h"
+
+
+int dfs_statfs(const char *path, struct statvfs *st)
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+ int ret;
+
+ TRACE1("statfs",path)
+
+ assert(path);
+ assert(st);
+ assert(dfs);
+
+ memset(st,0,sizeof(struct statvfs));
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+
+ const tOffset cap = hdfsGetCapacity(fs);
+ const tOffset used = hdfsGetUsed(fs);
+ const tOffset bsize = hdfsGetDefaultBlockSize(fs);
+
+ st->f_bsize = bsize;
+ st->f_frsize = bsize;
+ st->f_blocks = cap/bsize;
+ st->f_bfree = (cap-used)/bsize;
+ st->f_bavail = (cap-used)/bsize;
+ st->f_files = 1000;
+ st->f_ffree = 500;
+ st->f_favail = 500;
+ st->f_fsid = 1023;
+ st->f_flag = ST_RDONLY | ST_NOSUID;
+ st->f_namemax = 1023;
+ ret = 0;
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_symlink.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_symlink.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_symlink.c
new file mode 100644
index 0000000..be6e7eb
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_symlink.c
@@ -0,0 +1,30 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+
+
+int dfs_symlink(const char *from, const char *to)
+{
+ TRACE1("symlink", from)
+ (void)from;
+ (void)to;
+ // bugbug we need the FileSystem to support this posix API
+ return -ENOTSUP;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_truncate.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_truncate.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_truncate.c
new file mode 100644
index 0000000..bf72ca6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_truncate.c
@@ -0,0 +1,79 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_connect.h"
+
+/**
+ * For now implement truncate here and only for size == 0.
+ * Weak implementation in that we just delete the file and
+ * then re-create it, but don't set the user, group, and times to the old
+ * file's metadata.
+ */
+int dfs_truncate(const char *path, off_t size)
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ TRACE1("truncate", path)
+
+ assert(path);
+ assert('/' == *path);
+ assert(dfs);
+
+ if (size != 0) {
+ return 0;
+ }
+
+ int ret = dfs_unlink(path);
+ if (ret != 0) {
+ return ret;
+ }
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+
+ int flags = O_WRONLY | O_CREAT;
+
+ hdfsFile file;
+ if ((file = (hdfsFile)hdfsOpenFile(fs, path, flags, 0, 0, 0)) == NULL) {
+ ERROR("Could not connect open file %s", path);
+ ret = -EIO;
+ goto cleanup;
+ }
+
+ if (hdfsCloseFile(fs, file) != 0) {
+ ERROR("Could not close file %s", path);
+ ret = -EIO;
+ goto cleanup;
+ }
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_unlink.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_unlink.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_unlink.c
new file mode 100644
index 0000000..45a4501
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_unlink.c
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_connect.h"
+#include "fuse_trash.h"
+
+int dfs_unlink(const char *path)
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ int ret = 0;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ TRACE1("unlink", path)
+
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+
+ if (is_protected(path)) {
+ ERROR("Trying to delete protected directory %s", path);
+ ret = -EACCES;
+ goto cleanup;
+ }
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+
+ if (hdfsDeleteWithTrash(fs, path, dfs->usetrash)) {
+ ERROR("Could not delete file %s", path);
+ ret = (errno > 0) ? -errno : -EIO;
+ goto cleanup;
+ }
+ ret = 0;
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_utimens.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_utimens.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_utimens.c
new file mode 100644
index 0000000..dccff92
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_utimens.c
@@ -0,0 +1,70 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_connect.h"
+
+int dfs_utimens(const char *path, const struct timespec ts[2])
+{
+ struct hdfsConn *conn = NULL;
+ hdfsFS fs;
+ int ret = 0;
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+
+ TRACE1("utimens", path)
+
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+
+ time_t aTime = ts[0].tv_sec;
+ time_t mTime = ts[1].tv_sec;
+
+ ret = fuseConnectAsThreadUid(&conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
+ "connection! error %d.\n", ret);
+ ret = -EIO;
+ goto cleanup;
+ }
+ fs = hdfsConnGetFs(conn);
+
+ if (hdfsUtime(fs, path, mTime, aTime)) {
+ hdfsFileInfo *info = hdfsGetPathInfo(fs, path);
+ if (info == NULL) {
+ ret = (errno > 0) ? -errno : -ENOENT;
+ goto cleanup;
+ }
+ // Silently ignore utimens failure for directories, otherwise
+ // some programs like tar will fail.
+ if (info->mKind == kObjectKindDirectory) {
+ ret = 0;
+ } else {
+ ret = (errno > 0) ? -errno : -EACCES;
+ }
+ goto cleanup;
+ }
+ ret = 0;
+
+cleanup:
+ if (conn) {
+ hdfsConnRelease(conn);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_write.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_write.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_write.c
new file mode 100644
index 0000000..3090e9e
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_write.c
@@ -0,0 +1,83 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_connect.h"
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_file_handle.h"
+
+int dfs_write(const char *path, const char *buf, size_t size,
+ off_t offset, struct fuse_file_info *fi)
+{
+ TRACE1("write", path)
+
+ // retrieve dfs specific data
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+ int ret = 0;
+
+ // check params and the context var
+ assert(path);
+ assert(dfs);
+ assert('/' == *path);
+ assert(fi);
+
+ dfs_fh *fh = (dfs_fh*)fi->fh;
+ assert(fh);
+
+ hdfsFile file_handle = (hdfsFile)fh->hdfsFH;
+ assert(file_handle);
+
+ //
+ // Critical section - make the sanity check (tell to see the writes are sequential) and the actual write
+ // (no returns until end)
+ //
+ pthread_mutex_lock(&fh->mutex);
+
+ tSize length = 0;
+ hdfsFS fs = hdfsConnGetFs(fh->conn);
+
+ tOffset cur_offset = hdfsTell(fs, file_handle);
+ if (cur_offset != offset) {
+ ERROR("User trying to random access write to a file %d != %d for %s",
+ (int)cur_offset, (int)offset, path);
+ ret = -ENOTSUP;
+ } else {
+ length = hdfsWrite(fs, file_handle, buf, size);
+ if (length <= 0) {
+ ERROR("Could not write all bytes for %s %d != %d (errno=%d)",
+ path, length, (int)size, errno);
+ if (errno == 0 || errno == EINTERNAL) {
+ ret = -EIO;
+ } else {
+ ret = -errno;
+ }
+ }
+ if (length != size) {
+ ERROR("Could not write all bytes for %s %d != %d (errno=%d)",
+ path, length, (int)size, errno);
+ }
+ }
+
+ //
+ // Critical section end
+ //
+
+ pthread_mutex_unlock(&fh->mutex);
+
+ return ret == 0 ? length : ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_init.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_init.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_init.c
new file mode 100644
index 0000000..4da6da0
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_init.c
@@ -0,0 +1,192 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_init.h"
+#include "fuse_options.h"
+#include "fuse_context_handle.h"
+#include "fuse_connect.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static void print_env_vars(void)
+{
+ const char *cp = getenv("CLASSPATH");
+ const char *ld = getenv("LD_LIBRARY_PATH");
+
+ ERROR("LD_LIBRARY_PATH=%s",ld == NULL ? "NULL" : ld);
+ ERROR("CLASSPATH=%s",cp == NULL ? "NULL" : cp);
+}
+
+// Hacked up function to basically do:
+// protectedpaths = split(options.protected,':');
+
+static void init_protectedpaths(dfs_context *dfs)
+{
+ char *tmp = options.protected;
+
+ // handle degenerate case up front.
+ if (tmp == NULL || 0 == *tmp) {
+ dfs->protectedpaths = (char**)malloc(sizeof(char*));
+ dfs->protectedpaths[0] = NULL;
+ return;
+ }
+
+ if (options.debug) {
+ print_options();
+ }
+
+ int i = 0;
+ while (tmp && (NULL != (tmp = index(tmp,':')))) {
+ tmp++; // pass the ,
+ i++;
+ }
+ i++; // for the last entry
+ i++; // for the final NULL
+ dfs->protectedpaths = (char**)malloc(sizeof(char*)*i);
+ assert(dfs->protectedpaths);
+ tmp = options.protected;
+ int j = 0;
+ while (NULL != tmp && j < i) {
+ int length;
+ char *eos = index(tmp,':');
+ if (NULL != eos) {
+ length = eos - tmp; // length of this value
+ } else {
+ length = strlen(tmp);
+ }
+ dfs->protectedpaths[j] = (char*)malloc(sizeof(char)*length+1);
+ assert(dfs->protectedpaths[j]);
+ strncpy(dfs->protectedpaths[j], tmp, length);
+ dfs->protectedpaths[j][length] = '\0';
+ if (eos) {
+ tmp = eos + 1;
+ } else {
+ tmp = NULL;
+ }
+ j++;
+ }
+ dfs->protectedpaths[j] = NULL;
+}
+
+static void dfsPrintOptions(FILE *fp, const struct options *o)
+{
+ INFO("Mounting with options: [ protected=%s, nn_uri=%s, nn_port=%d, "
+ "debug=%d, read_only=%d, initchecks=%d, "
+ "no_permissions=%d, usetrash=%d, entry_timeout=%d, "
+ "attribute_timeout=%d, rdbuffer_size=%zd, direct_io=%d ]",
+ (o->protected ? o->protected : "(NULL)"), o->nn_uri, o->nn_port,
+ o->debug, o->read_only, o->initchecks,
+ o->no_permissions, o->usetrash, o->entry_timeout,
+ o->attribute_timeout, o->rdbuffer_size, o->direct_io);
+}
+
+void *dfs_init(struct fuse_conn_info *conn)
+{
+ int ret;
+
+ //
+ // Create a private struct of data we will pass to fuse here and which
+ // will then be accessible on every call.
+ //
+ dfs_context *dfs = calloc(1, sizeof(*dfs));
+ if (!dfs) {
+ ERROR("FATAL: could not malloc dfs_context");
+ exit(1);
+ }
+
+ // initialize the context
+ dfs->debug = options.debug;
+ dfs->usetrash = options.usetrash;
+ dfs->protectedpaths = NULL;
+ dfs->rdbuffer_size = options.rdbuffer_size;
+ dfs->direct_io = options.direct_io;
+
+ dfsPrintOptions(stderr, &options);
+
+ init_protectedpaths(dfs);
+ assert(dfs->protectedpaths != NULL);
+
+ if (dfs->rdbuffer_size <= 0) {
+ DEBUG("dfs->rdbuffersize <= 0 = %zd", dfs->rdbuffer_size);
+ dfs->rdbuffer_size = 32768;
+ }
+
+ ret = fuseConnectInit(options.nn_uri, options.nn_port);
+ if (ret) {
+ ERROR("FATAL: dfs_init: fuseConnectInit failed with error %d!", ret);
+ print_env_vars();
+ exit(EXIT_FAILURE);
+ }
+ if (options.initchecks == 1) {
+ ret = fuseConnectTest();
+ if (ret) {
+ ERROR("FATAL: dfs_init: fuseConnectTest failed with error %d!", ret);
+ print_env_vars();
+ exit(EXIT_FAILURE);
+ }
+ }
+
+#ifdef FUSE_CAP_ATOMIC_O_TRUNC
+ // If FUSE_CAP_ATOMIC_O_TRUNC is set, open("foo", O_CREAT | O_TRUNC) will
+ // result in dfs_open being called with O_TRUNC.
+ //
+ // If this capability is not present, fuse will try to use multiple
+ // operation to "simulate" open(O_TRUNC). This doesn't work very well with
+ // HDFS.
+ // Unfortunately, this capability is only implemented on Linux 2.6.29 or so.
+ // See HDFS-4140 for details.
+ if (conn->capable & FUSE_CAP_ATOMIC_O_TRUNC) {
+ conn->want |= FUSE_CAP_ATOMIC_O_TRUNC;
+ }
+#endif
+
+#ifdef FUSE_CAP_ASYNC_READ
+ // We're OK with doing reads at the same time as writes.
+ if (conn->capable & FUSE_CAP_ASYNC_READ) {
+ conn->want |= FUSE_CAP_ASYNC_READ;
+ }
+#endif
+
+#ifdef FUSE_CAP_BIG_WRITES
+ // Yes, we can read more than 4kb at a time. In fact, please do!
+ if (conn->capable & FUSE_CAP_BIG_WRITES) {
+ conn->want |= FUSE_CAP_BIG_WRITES;
+ }
+#endif
+
+#ifdef FUSE_CAP_DONT_MASK
+ if ((options.no_permissions) && (conn->capable & FUSE_CAP_DONT_MASK)) {
+ // If we're handing permissions ourselves, we don't want the kernel
+ // applying its own umask. HDFS already implements its own per-user
+ // umasks! Sadly, this only actually does something on kernels 2.6.31 and
+ // later.
+ conn->want |= FUSE_CAP_DONT_MASK;
+ }
+#endif
+
+ return (void*)dfs;
+}
+
+
+void dfs_destroy(void *ptr)
+{
+ TRACE("destroy")
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_init.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_init.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_init.h
new file mode 100644
index 0000000..681ab91
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_init.h
@@ -0,0 +1,33 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_INIT_H__
+#define __FUSE_INIT_H__
+
+struct fuse_conn_info;
+
+/**
+ * These are responsible for initializing connections to dfs and internal
+ * data structures and then freeing them.
+ * i.e., what happens on mount and unmount.
+ *
+ */
+void *dfs_init(struct fuse_conn_info *conn);
+void dfs_destroy (void *ptr);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_options.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_options.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_options.c
new file mode 100644
index 0000000..8461ce4
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_options.c
@@ -0,0 +1,188 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_context_handle.h"
+#include "fuse_dfs.h"
+#include "fuse_options.h"
+
+#include <getopt.h>
+#include <stdlib.h>
+
+#define OLD_HDFS_URI_LOCATION "dfs://"
+#define NEW_HDFS_URI_LOCATION "hdfs://"
+
+void print_options() {
+ printf("options:\n"
+ "\tprotected=%s\n"
+ "\tserver=%s\n"
+ "\tport=%d\n"
+ "\tdebug=%d\n"
+ "\tread_only=%d\n"
+ "\tusetrash=%d\n"
+ "\tentry_timeout=%d\n"
+ "\tattribute_timeout=%d\n"
+ "\tprivate=%d\n"
+ "\trdbuffer_size=%d (KBs)\n",
+ options.protected, options.nn_uri, options.nn_port, options.debug,
+ options.read_only, options.usetrash, options.entry_timeout,
+ options.attribute_timeout, options.private,
+ (int)options.rdbuffer_size / 1024);
+}
+
+const char *program;
+
+/** macro to define options */
+#define DFSFS_OPT_KEY(t, p, v) { t, offsetof(struct options, p), v }
+
+void print_usage(const char *pname)
+{
+ printf("USAGE: %s [debug] [--help] [--version] "
+ "[-oprotected=<colon_seped_list_of_paths] [rw] [-onotrash] "
+ "[-ousetrash] [-obig_writes] [-oprivate (single user)] [ro] "
+ "[-oserver=<hadoop_servername>] [-oport=<hadoop_port>] "
+ "[-oentry_timeout=<secs>] [-oattribute_timeout=<secs>] "
+ "[-odirect_io] [-onopoermissions] [-o<other fuse option>] "
+ "<mntpoint> [fuse options]\n", pname);
+ printf("NOTE: debugging option for fuse is -debug\n");
+}
+
+
+/** keys for FUSE_OPT_ options */
+enum
+ {
+ KEY_VERSION,
+ KEY_HELP,
+ KEY_USETRASH,
+ KEY_NOTRASH,
+ KEY_RO,
+ KEY_RW,
+ KEY_PRIVATE,
+ KEY_BIGWRITES,
+ KEY_DEBUG,
+ KEY_INITCHECKS,
+ KEY_NOPERMISSIONS,
+ KEY_DIRECTIO,
+ };
+
+struct fuse_opt dfs_opts[] =
+ {
+ DFSFS_OPT_KEY("server=%s", nn_uri, 0),
+ DFSFS_OPT_KEY("entry_timeout=%d", entry_timeout, 0),
+ DFSFS_OPT_KEY("attribute_timeout=%d", attribute_timeout, 0),
+ DFSFS_OPT_KEY("protected=%s", protected, 0),
+ DFSFS_OPT_KEY("port=%d", nn_port, 0),
+ DFSFS_OPT_KEY("rdbuffer=%d", rdbuffer_size,0),
+
+ FUSE_OPT_KEY("private", KEY_PRIVATE),
+ FUSE_OPT_KEY("ro", KEY_RO),
+ FUSE_OPT_KEY("debug", KEY_DEBUG),
+ FUSE_OPT_KEY("initchecks", KEY_INITCHECKS),
+ FUSE_OPT_KEY("nopermissions", KEY_NOPERMISSIONS),
+ FUSE_OPT_KEY("big_writes", KEY_BIGWRITES),
+ FUSE_OPT_KEY("rw", KEY_RW),
+ FUSE_OPT_KEY("usetrash", KEY_USETRASH),
+ FUSE_OPT_KEY("notrash", KEY_NOTRASH),
+ FUSE_OPT_KEY("direct_io", KEY_DIRECTIO),
+ FUSE_OPT_KEY("-v", KEY_VERSION),
+ FUSE_OPT_KEY("--version", KEY_VERSION),
+ FUSE_OPT_KEY("-h", KEY_HELP),
+ FUSE_OPT_KEY("--help", KEY_HELP),
+ FUSE_OPT_END
+ };
+
+int dfs_options(void *data, const char *arg, int key, struct fuse_args *outargs)
+{
+ (void) data;
+ int nn_uri_len;
+
+ switch (key) {
+ case FUSE_OPT_KEY_OPT:
+ INFO("Ignoring option %s", arg);
+ return 1;
+ case KEY_VERSION:
+ INFO("%s %s\n", program, _FUSE_DFS_VERSION);
+ exit(0);
+ case KEY_HELP:
+ print_usage(program);
+ exit(0);
+ case KEY_USETRASH:
+ options.usetrash = 1;
+ break;
+ case KEY_NOTRASH:
+ options.usetrash = 0;
+ break;
+ case KEY_RO:
+ options.read_only = 1;
+ break;
+ case KEY_RW:
+ options.read_only = 0;
+ break;
+ case KEY_PRIVATE:
+ options.private = 1;
+ break;
+ case KEY_DEBUG:
+ fuse_opt_add_arg(outargs, "-d");
+ options.debug = 1;
+ break;
+ case KEY_INITCHECKS:
+ options.initchecks = 1;
+ break;
+ case KEY_NOPERMISSIONS:
+ options.no_permissions = 1;
+ break;
+ case KEY_DIRECTIO:
+ options.direct_io = 1;
+ break;
+ case KEY_BIGWRITES:
+#ifdef FUSE_CAP_BIG_WRITES
+ fuse_opt_add_arg(outargs, "-obig_writes");
+#endif
+ break;
+ default: {
+ // try and see if the arg is a URI
+ if (!strstr(arg, "://")) {
+ if (strcmp(arg,"ro") == 0) {
+ options.read_only = 1;
+ } else if (strcmp(arg,"rw") == 0) {
+ options.read_only = 0;
+ } else {
+ INFO("Adding FUSE arg %s", arg);
+ fuse_opt_add_arg(outargs, arg);
+ return 0;
+ }
+ } else {
+ if (options.nn_uri) {
+ INFO("Ignoring option %s because '-server' was already "
+ "specified!", arg);
+ return 1;
+ }
+ if (strstr(arg, OLD_HDFS_URI_LOCATION) == arg) {
+ // For historical reasons, we let people refer to hdfs:// as dfs://
+ nn_uri_len = strlen(NEW_HDFS_URI_LOCATION) +
+ strlen(arg + strlen(OLD_HDFS_URI_LOCATION)) + 1;
+ options.nn_uri = malloc(nn_uri_len);
+ snprintf(options.nn_uri, nn_uri_len, "%s%s", NEW_HDFS_URI_LOCATION,
+ arg + strlen(OLD_HDFS_URI_LOCATION));
+ } else {
+ options.nn_uri = strdup(arg);
+ }
+ }
+ }
+ }
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_options.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_options.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_options.h
new file mode 100644
index 0000000..4bfc235
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_options.h
@@ -0,0 +1,44 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_OPTIONS_H__
+#define __FUSE_OPTIONS_H__
+
+/** options for fuse_opt.h */
+struct options {
+ char* protected;
+ char* nn_uri;
+ int nn_port;
+ int debug;
+ int read_only;
+ int initchecks;
+ int no_permissions;
+ int usetrash;
+ int entry_timeout;
+ int attribute_timeout;
+ int private;
+ size_t rdbuffer_size;
+ int direct_io;
+} options;
+
+extern struct fuse_opt dfs_opts[];
+void print_options();
+void print_usage(const char *pname);
+int dfs_options(void *data, const char *arg, int key, struct fuse_args *outargs);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_stat_struct.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_stat_struct.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_stat_struct.c
new file mode 100644
index 0000000..e3a0725
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_stat_struct.c
@@ -0,0 +1,112 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include <math.h>
+#include <pthread.h>
+#include <grp.h>
+#include <pwd.h>
+
+#include "fuse_dfs.h"
+#include "fuse_stat_struct.h"
+#include "fuse_context_handle.h"
+
+/*
+ * getpwuid and getgrgid return static structs so we safeguard the contents
+ * while retrieving fields using the 2 structs below.
+ * NOTE: if using both, always get the passwd struct firt!
+ */
+extern pthread_mutex_t passwdstruct_mutex;
+extern pthread_mutex_t groupstruct_mutex;
+
+const int default_id = 99; // nobody - not configurable since soon uids in dfs, yeah!
+const int blksize = 512;
+
+/**
+ * Converts from a hdfs hdfsFileInfo to a POSIX stat struct
+ *
+ */
+int fill_stat_structure(hdfsFileInfo *info, struct stat *st)
+{
+ assert(st);
+ assert(info);
+
+ // initialize the stat structure
+ memset(st, 0, sizeof(struct stat));
+
+ // by default: set to 0 to indicate not supported for directory because we cannot (efficiently) get this info for every subdirectory
+ st->st_nlink = (info->mKind == kObjectKindDirectory) ? 0 : 1;
+
+ uid_t owner_id = default_id;
+ if (info->mOwner != NULL) {
+ //
+ // Critical section - protect from concurrent calls in different threads since
+ // the struct below is static.
+ // (no returns until end)
+ //
+ pthread_mutex_lock(&passwdstruct_mutex);
+
+ struct passwd *passwd_info = getpwnam(info->mOwner);
+ owner_id = passwd_info == NULL ? default_id : passwd_info->pw_uid;
+
+ //
+ // End critical section
+ //
+ pthread_mutex_unlock(&passwdstruct_mutex);
+
+ }
+
+ gid_t group_id = default_id;
+
+ if (info->mGroup != NULL) {
+ //
+ // Critical section - protect from concurrent calls in different threads since
+ // the struct below is static.
+ // (no returns until end)
+ //
+ pthread_mutex_lock(&groupstruct_mutex);
+
+ struct group *grp = getgrnam(info->mGroup);
+ group_id = grp == NULL ? default_id : grp->gr_gid;
+
+ //
+ // End critical section
+ //
+ pthread_mutex_unlock(&groupstruct_mutex);
+
+ }
+
+ short perm = (info->mKind == kObjectKindDirectory) ? (S_IFDIR | 0777) : (S_IFREG | 0666);
+ if (info->mPermissions > 0) {
+ perm = (info->mKind == kObjectKindDirectory) ? S_IFDIR: S_IFREG ;
+ perm |= info->mPermissions;
+ }
+
+ // set stat metadata
+ st->st_size = (info->mKind == kObjectKindDirectory) ? 4096 : info->mSize;
+ st->st_blksize = blksize;
+ st->st_blocks = ceil(st->st_size/st->st_blksize);
+ st->st_mode = perm;
+ st->st_uid = owner_id;
+ st->st_gid = group_id;
+ st->st_atime = info->mLastAccess;
+ st->st_mtime = info->mLastMod;
+ st->st_ctime = info->mLastMod;
+
+ return 0;
+}
+
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_stat_struct.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_stat_struct.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_stat_struct.h
new file mode 100644
index 0000000..d42a371
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_stat_struct.h
@@ -0,0 +1,36 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_STAT_STRUCT_H__
+#define __FUSE_STAT_STRUCT_H__
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "hdfs.h"
+
+/**
+ * Converts from a hdfs hdfsFileInfo to a POSIX stat struct
+ * Should be thread safe.
+ */
+int fill_stat_structure(hdfsFileInfo *info, struct stat *st) ;
+
+extern const int default_id;
+extern const int blksize;
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_trash.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_trash.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_trash.c
new file mode 100644
index 0000000..5e58087
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_trash.c
@@ -0,0 +1,244 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include <hdfs.h>
+#include <inttypes.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+
+#include "fuse_context_handle.h"
+#include "fuse_dfs.h"
+#include "fuse_trash.h"
+#include "fuse_users.h"
+
+#define TRASH_RENAME_TRIES 100
+#define ALREADY_IN_TRASH_ERR 9000
+
+/**
+ * Split a path into a parent directory and a base path component.
+ *
+ * @param abs_path The absolute path.
+ * @param pcomp (out param) Will be set to the last path component.
+ * Malloced.
+ * @param parent_dir (out param) Will be set to the parent directory.
+ * Malloced.
+ *
+ * @return 0 on success.
+ * On success, both *pcomp and *parent_dir will contain
+ * malloc'ed strings.
+ * EINVAL if the path wasn't absolute.
+ * EINVAL if there is no parent directory (i.e. abs_path=/)
+ * ENOMEM if we ran out of memory.
+ */
+static int get_parent_dir(const char *abs_path, char **pcomp,
+ char **parent_dir)
+{
+ int ret;
+ char *pdir = NULL, *pc = NULL, *last_slash;
+
+ pdir = strdup(abs_path);
+ if (!pdir) {
+ ret = ENOMEM;
+ goto done;
+ }
+ last_slash = rindex(pdir, '/');
+ if (!last_slash) {
+ ERROR("get_parent_dir(%s): expected absolute path.\n", abs_path);
+ ret = EINVAL;
+ goto done;
+ }
+ if (last_slash[1] == '\0') {
+ *last_slash = '\0';
+ last_slash = rindex(pdir, '/');
+ if (!last_slash) {
+ ERROR("get_parent_dir(%s): there is no parent dir.\n", abs_path);
+ ret = EINVAL;
+ goto done;
+ }
+ }
+ pc = strdup(last_slash + 1);
+ if (!pc) {
+ ret = ENOMEM;
+ goto done;
+ }
+ *last_slash = '\0';
+ ret = 0;
+done:
+ if (ret) {
+ free(pdir);
+ free(pc);
+ return ret;
+ }
+ *pcomp = pc;
+ *parent_dir = pdir;
+ return 0;
+}
+
+/**
+ * Get the base path to the trash. This will depend on the user ID.
+ * For example, a user whose ID maps to 'foo' will get back the path
+ * "/user/foo/.Trash/Current".
+ *
+ * @param trash_base (out param) the base path to the trash.
+ * Malloced.
+ *
+ * @return 0 on success; error code otherwise.
+ */
+static int get_trash_base(char **trash_base)
+{
+ const char * const PREFIX = "/user/";
+ const char * const SUFFIX = "/.Trash/Current";
+ char *user_name = NULL, *base = NULL;
+ uid_t uid = fuse_get_context()->uid;
+ int ret;
+
+ user_name = getUsername(uid);
+ if (!user_name) {
+ ERROR("get_trash_base(): failed to get username for uid %"PRId64"\n",
+ (uint64_t)uid);
+ ret = EIO;
+ goto done;
+ }
+ if (asprintf(&base, "%s%s%s", PREFIX, user_name, SUFFIX) < 0) {
+ base = NULL;
+ ret = ENOMEM;
+ goto done;
+ }
+ ret = 0;
+done:
+ free(user_name);
+ if (ret) {
+ free(base);
+ return ret;
+ }
+ *trash_base = base;
+ return 0;
+}
+
+//
+// NOTE: this function is a c implementation of org.apache.hadoop.fs.Trash.moveToTrash(Path path).
+//
+int move_to_trash(const char *abs_path, hdfsFS userFS)
+{
+ int ret;
+ char *pcomp = NULL, *parent_dir = NULL, *trash_base = NULL;
+ char *target_dir = NULL, *target = NULL;
+
+ ret = get_parent_dir(abs_path, &pcomp, &parent_dir);
+ if (ret) {
+ goto done;
+ }
+ ret = get_trash_base(&trash_base);
+ if (ret) {
+ goto done;
+ }
+ int trash_base_len = strlen(trash_base);
+ if (!strncmp(trash_base, abs_path, trash_base_len)
+ && (strlen(abs_path) == trash_base_len || abs_path[trash_base_len] == '/')) {
+ INFO("move_to_trash(%s): file is already in the trash; deleting.",
+ abs_path);
+ ret = ALREADY_IN_TRASH_ERR;
+ goto done;
+ }
+ if (asprintf(&target_dir, "%s%s", trash_base, parent_dir) < 0) {
+ ret = ENOMEM;
+ target_dir = NULL;
+ goto done;
+ }
+ if (asprintf(&target, "%s/%s", target_dir, pcomp) < 0) {
+ ret = ENOMEM;
+ target = NULL;
+ goto done;
+ }
+ // create the target trash directory in trash (if needed)
+ if (hdfsExists(userFS, target_dir) != 0) {
+ // make the directory to put it in in the Trash - NOTE
+ // hdfsCreateDirectory also creates parents, so Current will be created if it does not exist.
+ if (hdfsCreateDirectory(userFS, target_dir)) {
+ ret = errno;
+ ERROR("move_to_trash(%s) error: hdfsCreateDirectory(%s) failed with error %d",
+ abs_path, target_dir, ret);
+ goto done;
+ }
+ } else if (hdfsExists(userFS, target) == 0) {
+ // If there is already a file in the trash with this path, append a number.
+ int idx;
+ for (idx = 1; idx < TRASH_RENAME_TRIES; idx++) {
+ free(target);
+ if (asprintf(&target, "%s/%s.%d", target_dir, pcomp, idx) < 0) {
+ target = NULL;
+ ret = ENOMEM;
+ goto done;
+ }
+ if (hdfsExists(userFS, target) != 0) {
+ break;
+ }
+ }
+ if (idx == TRASH_RENAME_TRIES) {
+ ERROR("move_to_trash(%s) error: there are already %d files in the trash "
+ "with this name.\n", abs_path, TRASH_RENAME_TRIES);
+ ret = EINVAL;
+ goto done;
+ }
+ }
+ if (hdfsRename(userFS, abs_path, target)) {
+ ret = errno;
+ ERROR("move_to_trash(%s): failed to rename the file to %s: error %d",
+ abs_path, target, ret);
+ goto done;
+ }
+
+ ret = 0;
+done:
+ if ((ret != 0) && (ret != ALREADY_IN_TRASH_ERR)) {
+ ERROR("move_to_trash(%s) failed with error %d", abs_path, ret);
+ }
+ free(pcomp);
+ free(parent_dir);
+ free(trash_base);
+ free(target_dir);
+ free(target);
+ return ret;
+}
+
+int hdfsDeleteWithTrash(hdfsFS userFS, const char *path, int useTrash)
+{
+ int tried_to_move_to_trash = 0;
+ if (useTrash) {
+ tried_to_move_to_trash = 1;
+ if (move_to_trash(path, userFS) == 0) {
+ return 0;
+ }
+ }
+ if (hdfsDelete(userFS, path, 1)) {
+ int err = errno;
+ if (err < 0) {
+ err = -err;
+ }
+ ERROR("hdfsDeleteWithTrash(%s): hdfsDelete failed: error %d.",
+ path, err);
+ return -err;
+ }
+ if (tried_to_move_to_trash) {
+ ERROR("hdfsDeleteWithTrash(%s): deleted the file instead.\n", path);
+ }
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_trash.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_trash.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_trash.h
new file mode 100644
index 0000000..220ce3d
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_trash.h
@@ -0,0 +1,26 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_TRASH_H__
+#define __FUSE_TRASH_H__
+
+#include <hdfs.h>
+
+int hdfsDeleteWithTrash(hdfsFS userFS, const char *path, int useTrash);
+
+#endif
[29/35] hadoop git commit: HDFS-9209. Erasure coding: Add apache
license header in TestFileStatusWithECPolicy.java. Contributed by Surendra
Singh Lilhore.
Posted by ji...@apache.org.
HDFS-9209. Erasure coding: Add apache license header in TestFileStatusWithECPolicy.java. Contributed by Surendra Singh Lilhore.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/fde729fe
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/fde729fe
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/fde729fe
Branch: refs/heads/HDFS-8966
Commit: fde729feeb67af18f7d9b1cd156750ec9e8d3304
Parents: 6dd47d7
Author: Jing Zhao <ji...@apache.org>
Authored: Wed Oct 7 15:17:50 2015 -0700
Committer: Jing Zhao <ji...@apache.org>
Committed: Wed Oct 7 15:17:50 2015 -0700
----------------------------------------------------------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +++
.../hadoop/hdfs/TestFileStatusWithECPolicy.java | 17 +++++++++++++++++
2 files changed, 20 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/fde729fe/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index c1343e4..bd539ab 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -817,6 +817,9 @@ Trunk (Unreleased)
HDFS-9206. Inconsistent default value of dfs.datanode.stripedread.buffer.size.
(Walter Su via jing9)
+ HDFS-9209. Erasure coding: Add apache license header in
+ TestFileStatusWithECPolicy.java. (Surendra Singh Lilhore via jing9)
+
Release 2.8.0 - UNRELEASED
NEW FEATURES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/fde729fe/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestFileStatusWithECPolicy.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestFileStatusWithECPolicy.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestFileStatusWithECPolicy.java
index 64063d2..33bea0f 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestFileStatusWithECPolicy.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestFileStatusWithECPolicy.java
@@ -1,3 +1,20 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
package org.apache.hadoop.hdfs;
import static org.junit.Assert.assertNotNull;
[31/35] hadoop git commit: HDFS-9137. DeadLock between
DataNode#refreshVolumes and BPOfferService#registrationSucceeded. (Uma
Maheswara Rao G via yliu)
Posted by ji...@apache.org.
HDFS-9137. DeadLock between DataNode#refreshVolumes and BPOfferService#registrationSucceeded. (Uma Maheswara Rao G via yliu)
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/35affec3
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/35affec3
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/35affec3
Branch: refs/heads/HDFS-8966
Commit: 35affec38e17e3f9c21d36be111171476072c03f
Parents: 66e2cfa
Author: yliu <yl...@apache.org>
Authored: Thu Oct 8 10:27:47 2015 +0800
Committer: yliu <yl...@apache.org>
Committed: Thu Oct 8 10:27:47 2015 +0800
----------------------------------------------------------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +++
.../hadoop/hdfs/server/datanode/DataNode.java | 25 +++++++++++++++-----
2 files changed, 22 insertions(+), 6 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/35affec3/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index ee6d19d..e05a618 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1983,6 +1983,9 @@ Release 2.8.0 - UNRELEASED
HDFS-9176. Fix TestDirectoryScanner#testThrottling often fails.
(Daniel Templeton via lei)
+ HDFS-9137. DeadLock between DataNode#refreshVolumes and
+ BPOfferService#registrationSucceeded. (Uma Maheswara Rao G via yliu)
+
Release 2.7.2 - UNRELEASED
INCOMPATIBLE CHANGES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/35affec3/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
index 63b8847..b280067 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
@@ -497,12 +497,29 @@ public class DataNode extends ReconfigurableBase
public void reconfigurePropertyImpl(String property, String newVal)
throws ReconfigurationException {
if (property.equals(DFS_DATANODE_DATA_DIR_KEY)) {
+ IOException rootException = null;
try {
LOG.info("Reconfiguring " + property + " to " + newVal);
this.refreshVolumes(newVal);
} catch (IOException e) {
- throw new ReconfigurationException(property, newVal,
- getConf().get(property), e);
+ rootException = e;
+ } finally {
+ // Send a full block report to let NN acknowledge the volume changes.
+ try {
+ triggerBlockReport(
+ new BlockReportOptions.Factory().setIncremental(false).build());
+ } catch (IOException e) {
+ LOG.warn("Exception while sending the block report after refreshing"
+ + " volumes " + property + " to " + newVal, e);
+ if (rootException == null) {
+ rootException = e;
+ }
+ } finally {
+ if (rootException != null) {
+ throw new ReconfigurationException(property, newVal,
+ getConf().get(property), rootException);
+ }
+ }
}
} else {
throw new ReconfigurationException(
@@ -684,10 +701,6 @@ public class DataNode extends ReconfigurableBase
conf.set(DFS_DATANODE_DATA_DIR_KEY,
Joiner.on(",").join(effectiveVolumes));
dataDirs = getStorageLocations(conf);
-
- // Send a full block report to let NN acknowledge the volume changes.
- triggerBlockReport(new BlockReportOptions.Factory()
- .setIncremental(false).build());
}
}
[24/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
HDFS-9170. Move libhdfs / fuse-dfs / libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/3112f263
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/3112f263
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/3112f263
Branch: refs/heads/HDFS-8966
Commit: 3112f263688be6bf830c8386040f000be18f95da
Parents: 239d119
Author: Haohui Mai <wh...@apache.org>
Authored: Tue Sep 29 17:45:53 2015 -0700
Committer: Haohui Mai <wh...@apache.org>
Committed: Wed Oct 7 00:06:33 2015 -0700
----------------------------------------------------------------------
.../hadoop-hdfs-native-client/pom.xml | 230 ++
.../src/CMakeLists.txt | 92 +
.../src/config.h.cmake | 27 +
.../src/contrib/libwebhdfs/CMakeLists.txt | 87 +
.../libwebhdfs/resources/FindJansson.cmake | 43 +
.../contrib/libwebhdfs/src/hdfs_http_client.c | 490 +++
.../contrib/libwebhdfs/src/hdfs_http_client.h | 294 ++
.../contrib/libwebhdfs/src/hdfs_http_query.c | 402 +++
.../contrib/libwebhdfs/src/hdfs_http_query.h | 240 ++
.../contrib/libwebhdfs/src/hdfs_json_parser.c | 654 ++++
.../contrib/libwebhdfs/src/hdfs_json_parser.h | 178 +
.../src/contrib/libwebhdfs/src/hdfs_web.c | 1538 ++++++++
.../libwebhdfs/src/test_libwebhdfs_ops.c | 552 +++
.../libwebhdfs/src/test_libwebhdfs_read.c | 78 +
.../libwebhdfs/src/test_libwebhdfs_threaded.c | 247 ++
.../libwebhdfs/src/test_libwebhdfs_write.c | 111 +
.../src/main/native/fuse-dfs/CMakeLists.txt | 88 +
.../src/main/native/fuse-dfs/doc/README | 131 +
.../src/main/native/fuse-dfs/fuse_connect.c | 644 ++++
.../src/main/native/fuse-dfs/fuse_connect.h | 90 +
.../main/native/fuse-dfs/fuse_context_handle.h | 40 +
.../src/main/native/fuse-dfs/fuse_dfs.c | 136 +
.../src/main/native/fuse-dfs/fuse_dfs.h | 81 +
.../main/native/fuse-dfs/fuse_dfs_wrapper.sh | 46 +
.../src/main/native/fuse-dfs/fuse_file_handle.h | 46 +
.../src/main/native/fuse-dfs/fuse_impls.h | 63 +
.../main/native/fuse-dfs/fuse_impls_access.c | 29 +
.../src/main/native/fuse-dfs/fuse_impls_chmod.c | 57 +
.../src/main/native/fuse-dfs/fuse_impls_chown.c | 87 +
.../main/native/fuse-dfs/fuse_impls_create.c | 27 +
.../src/main/native/fuse-dfs/fuse_impls_flush.c | 54 +
.../main/native/fuse-dfs/fuse_impls_getattr.c | 75 +
.../src/main/native/fuse-dfs/fuse_impls_mkdir.c | 70 +
.../src/main/native/fuse-dfs/fuse_impls_mknod.c | 27 +
.../src/main/native/fuse-dfs/fuse_impls_open.c | 172 +
.../src/main/native/fuse-dfs/fuse_impls_read.c | 163 +
.../main/native/fuse-dfs/fuse_impls_readdir.c | 122 +
.../main/native/fuse-dfs/fuse_impls_release.c | 66 +
.../main/native/fuse-dfs/fuse_impls_rename.c | 66 +
.../src/main/native/fuse-dfs/fuse_impls_rmdir.c | 76 +
.../main/native/fuse-dfs/fuse_impls_statfs.c | 70 +
.../main/native/fuse-dfs/fuse_impls_symlink.c | 30 +
.../main/native/fuse-dfs/fuse_impls_truncate.c | 79 +
.../main/native/fuse-dfs/fuse_impls_unlink.c | 65 +
.../main/native/fuse-dfs/fuse_impls_utimens.c | 70 +
.../src/main/native/fuse-dfs/fuse_impls_write.c | 83 +
.../src/main/native/fuse-dfs/fuse_init.c | 192 +
.../src/main/native/fuse-dfs/fuse_init.h | 33 +
.../src/main/native/fuse-dfs/fuse_options.c | 188 +
.../src/main/native/fuse-dfs/fuse_options.h | 44 +
.../src/main/native/fuse-dfs/fuse_stat_struct.c | 112 +
.../src/main/native/fuse-dfs/fuse_stat_struct.h | 36 +
.../src/main/native/fuse-dfs/fuse_trash.c | 244 ++
.../src/main/native/fuse-dfs/fuse_trash.h | 26 +
.../src/main/native/fuse-dfs/fuse_users.c | 213 ++
.../src/main/native/fuse-dfs/fuse_users.h | 70 +
.../main/native/fuse-dfs/test/TestFuseDFS.java | 410 +++
.../main/native/fuse-dfs/test/fuse_workload.c | 403 +++
.../main/native/fuse-dfs/test/fuse_workload.h | 36 +
.../main/native/fuse-dfs/test/test_fuse_dfs.c | 378 ++
.../src/main/native/fuse-dfs/util/posix_util.c | 155 +
.../src/main/native/fuse-dfs/util/posix_util.h | 58 +
.../src/main/native/fuse-dfs/util/tree.h | 765 ++++
.../src/main/native/libhdfs/CMakeLists.txt | 141 +
.../src/main/native/libhdfs/common/htable.c | 287 ++
.../src/main/native/libhdfs/common/htable.h | 161 +
.../src/main/native/libhdfs/exception.c | 239 ++
.../src/main/native/libhdfs/exception.h | 157 +
.../src/main/native/libhdfs/expect.c | 68 +
.../src/main/native/libhdfs/expect.h | 179 +
.../src/main/native/libhdfs/hdfs.c | 3342 ++++++++++++++++++
.../src/main/native/libhdfs/hdfs.h | 939 +++++
.../src/main/native/libhdfs/hdfs_test.h | 64 +
.../src/main/native/libhdfs/jni_helper.c | 595 ++++
.../src/main/native/libhdfs/jni_helper.h | 161 +
.../src/main/native/libhdfs/native_mini_dfs.c | 357 ++
.../src/main/native/libhdfs/native_mini_dfs.h | 129 +
.../src/main/native/libhdfs/os/mutexes.h | 55 +
.../src/main/native/libhdfs/os/posix/mutexes.c | 43 +
.../src/main/native/libhdfs/os/posix/platform.h | 34 +
.../src/main/native/libhdfs/os/posix/thread.c | 52 +
.../libhdfs/os/posix/thread_local_storage.c | 80 +
.../src/main/native/libhdfs/os/thread.h | 54 +
.../native/libhdfs/os/thread_local_storage.h | 75 +
.../main/native/libhdfs/os/windows/inttypes.h | 28 +
.../main/native/libhdfs/os/windows/mutexes.c | 52 +
.../main/native/libhdfs/os/windows/platform.h | 86 +
.../src/main/native/libhdfs/os/windows/thread.c | 66 +
.../libhdfs/os/windows/thread_local_storage.c | 172 +
.../src/main/native/libhdfs/os/windows/unistd.h | 29 +
.../src/main/native/libhdfs/test/test_htable.c | 100 +
.../main/native/libhdfs/test/test_libhdfs_ops.c | 540 +++
.../native/libhdfs/test/test_libhdfs_read.c | 72 +
.../native/libhdfs/test/test_libhdfs_write.c | 99 +
.../native/libhdfs/test/test_libhdfs_zerocopy.c | 280 ++
.../src/main/native/libhdfs/test/vecsum.c | 825 +++++
.../main/native/libhdfs/test_libhdfs_threaded.c | 360 ++
.../main/native/libhdfs/test_native_mini_dfs.c | 41 +
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 2 +
hadoop-hdfs-project/hadoop-hdfs/pom.xml | 170 +-
.../hadoop-hdfs/src/CMakeLists.txt | 206 --
.../hadoop-hdfs/src/config.h.cmake | 27 -
.../src/contrib/libwebhdfs/CMakeLists.txt | 78 -
.../libwebhdfs/resources/FindJansson.cmake | 43 -
.../contrib/libwebhdfs/src/hdfs_http_client.c | 490 ---
.../contrib/libwebhdfs/src/hdfs_http_client.h | 294 --
.../contrib/libwebhdfs/src/hdfs_http_query.c | 402 ---
.../contrib/libwebhdfs/src/hdfs_http_query.h | 240 --
.../contrib/libwebhdfs/src/hdfs_json_parser.c | 654 ----
.../contrib/libwebhdfs/src/hdfs_json_parser.h | 178 -
.../src/contrib/libwebhdfs/src/hdfs_web.c | 1538 --------
.../libwebhdfs/src/test_libwebhdfs_ops.c | 552 ---
.../libwebhdfs/src/test_libwebhdfs_read.c | 78 -
.../libwebhdfs/src/test_libwebhdfs_threaded.c | 247 --
.../libwebhdfs/src/test_libwebhdfs_write.c | 111 -
.../src/main/native/fuse-dfs/CMakeLists.txt | 102 -
.../src/main/native/fuse-dfs/doc/README | 131 -
.../src/main/native/fuse-dfs/fuse_connect.c | 644 ----
.../src/main/native/fuse-dfs/fuse_connect.h | 90 -
.../main/native/fuse-dfs/fuse_context_handle.h | 40 -
.../src/main/native/fuse-dfs/fuse_dfs.c | 136 -
.../src/main/native/fuse-dfs/fuse_dfs.h | 81 -
.../main/native/fuse-dfs/fuse_dfs_wrapper.sh | 46 -
.../src/main/native/fuse-dfs/fuse_file_handle.h | 46 -
.../src/main/native/fuse-dfs/fuse_impls.h | 63 -
.../main/native/fuse-dfs/fuse_impls_access.c | 29 -
.../src/main/native/fuse-dfs/fuse_impls_chmod.c | 57 -
.../src/main/native/fuse-dfs/fuse_impls_chown.c | 87 -
.../main/native/fuse-dfs/fuse_impls_create.c | 27 -
.../src/main/native/fuse-dfs/fuse_impls_flush.c | 54 -
.../main/native/fuse-dfs/fuse_impls_getattr.c | 75 -
.../src/main/native/fuse-dfs/fuse_impls_mkdir.c | 70 -
.../src/main/native/fuse-dfs/fuse_impls_mknod.c | 27 -
.../src/main/native/fuse-dfs/fuse_impls_open.c | 172 -
.../src/main/native/fuse-dfs/fuse_impls_read.c | 163 -
.../main/native/fuse-dfs/fuse_impls_readdir.c | 122 -
.../main/native/fuse-dfs/fuse_impls_release.c | 66 -
.../main/native/fuse-dfs/fuse_impls_rename.c | 66 -
.../src/main/native/fuse-dfs/fuse_impls_rmdir.c | 76 -
.../main/native/fuse-dfs/fuse_impls_statfs.c | 70 -
.../main/native/fuse-dfs/fuse_impls_symlink.c | 30 -
.../main/native/fuse-dfs/fuse_impls_truncate.c | 79 -
.../main/native/fuse-dfs/fuse_impls_unlink.c | 65 -
.../main/native/fuse-dfs/fuse_impls_utimens.c | 70 -
.../src/main/native/fuse-dfs/fuse_impls_write.c | 83 -
.../src/main/native/fuse-dfs/fuse_init.c | 192 -
.../src/main/native/fuse-dfs/fuse_init.h | 33 -
.../src/main/native/fuse-dfs/fuse_options.c | 188 -
.../src/main/native/fuse-dfs/fuse_options.h | 44 -
.../src/main/native/fuse-dfs/fuse_stat_struct.c | 112 -
.../src/main/native/fuse-dfs/fuse_stat_struct.h | 36 -
.../src/main/native/fuse-dfs/fuse_trash.c | 244 --
.../src/main/native/fuse-dfs/fuse_trash.h | 26 -
.../src/main/native/fuse-dfs/fuse_users.c | 213 --
.../src/main/native/fuse-dfs/fuse_users.h | 70 -
.../main/native/fuse-dfs/test/TestFuseDFS.java | 410 ---
.../main/native/fuse-dfs/test/fuse_workload.c | 403 ---
.../main/native/fuse-dfs/test/fuse_workload.h | 36 -
.../main/native/fuse-dfs/test/test_fuse_dfs.c | 378 --
.../src/main/native/libhdfs/common/htable.c | 287 --
.../src/main/native/libhdfs/common/htable.h | 161 -
.../src/main/native/libhdfs/exception.c | 239 --
.../src/main/native/libhdfs/exception.h | 157 -
.../src/main/native/libhdfs/expect.c | 68 -
.../src/main/native/libhdfs/expect.h | 179 -
.../hadoop-hdfs/src/main/native/libhdfs/hdfs.c | 3342 ------------------
.../hadoop-hdfs/src/main/native/libhdfs/hdfs.h | 939 -----
.../src/main/native/libhdfs/hdfs_test.h | 64 -
.../src/main/native/libhdfs/jni_helper.c | 595 ----
.../src/main/native/libhdfs/jni_helper.h | 161 -
.../src/main/native/libhdfs/native_mini_dfs.c | 357 --
.../src/main/native/libhdfs/native_mini_dfs.h | 129 -
.../src/main/native/libhdfs/os/mutexes.h | 55 -
.../src/main/native/libhdfs/os/posix/mutexes.c | 43 -
.../src/main/native/libhdfs/os/posix/platform.h | 34 -
.../src/main/native/libhdfs/os/posix/thread.c | 52 -
.../libhdfs/os/posix/thread_local_storage.c | 80 -
.../src/main/native/libhdfs/os/thread.h | 54 -
.../native/libhdfs/os/thread_local_storage.h | 75 -
.../main/native/libhdfs/os/windows/inttypes.h | 28 -
.../main/native/libhdfs/os/windows/mutexes.c | 52 -
.../main/native/libhdfs/os/windows/platform.h | 86 -
.../src/main/native/libhdfs/os/windows/thread.c | 66 -
.../libhdfs/os/windows/thread_local_storage.c | 172 -
.../src/main/native/libhdfs/os/windows/unistd.h | 29 -
.../src/main/native/libhdfs/test/test_htable.c | 100 -
.../main/native/libhdfs/test/test_libhdfs_ops.c | 540 ---
.../native/libhdfs/test/test_libhdfs_read.c | 72 -
.../native/libhdfs/test/test_libhdfs_write.c | 99 -
.../native/libhdfs/test/test_libhdfs_zerocopy.c | 280 --
.../src/main/native/libhdfs/test/vecsum.c | 825 -----
.../main/native/libhdfs/test_libhdfs_threaded.c | 360 --
.../main/native/libhdfs/test_native_mini_dfs.c | 41 -
.../src/main/native/util/posix_util.c | 155 -
.../src/main/native/util/posix_util.h | 58 -
.../hadoop-hdfs/src/main/native/util/tree.h | 765 ----
hadoop-hdfs-project/pom.xml | 1 +
197 files changed, 21445 insertions(+), 21358 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/pom.xml b/hadoop-hdfs-project/hadoop-hdfs-native-client/pom.xml
new file mode 100644
index 0000000..5632c48
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/pom.xml
@@ -0,0 +1,230 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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. See accompanying LICENSE file.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
+http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-project-dist</artifactId>
+ <version>3.0.0-SNAPSHOT</version>
+ <relativePath>../../hadoop-project-dist</relativePath>
+ </parent>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs-native-client</artifactId>
+ <version>3.0.0-SNAPSHOT</version>
+ <description>Apache Hadoop HDFS Native Client</description>
+ <name>Apache Hadoop HDFS Native Client</name>
+ <packaging>jar</packaging>
+
+ <properties>
+ <require.fuse>false</require.fuse>
+ <require.libwebhdfs>false</require.libwebhdfs>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-common</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-common</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <profiles>
+ <profile>
+ <id>native-win</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ <os>
+ <family>windows</family>
+ </os>
+ </activation>
+ <properties>
+ <runningWithNative>true</runningWithNative>
+ </properties>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-enforcer-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>enforce-os</id>
+ <goals>
+ <goal>enforce</goal>
+ </goals>
+ <configuration>
+ <rules>
+ <requireOS>
+ <family>windows</family>
+ <message>native-win build only supported on Windows</message>
+ </requireOS>
+ </rules>
+ <fail>true</fail>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>make</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ <configuration>
+ <target>
+ <condition property="generator" value="Visual Studio 10" else="Visual Studio 10 Win64">
+ <equals arg1="Win32" arg2="${env.PLATFORM}" />
+ </condition>
+ <mkdir dir="${project.build.directory}/native"/>
+ <exec executable="cmake" dir="${project.build.directory}/native"
+ failonerror="true">
+ <arg line="${basedir}/src/ -DGENERATED_JAVAH=${project.build.directory}/native/javah -DJVM_ARCH_DATA_MODEL=${sun.arch.data.model} -DREQUIRE_LIBWEBHDFS=${require.libwebhdfs} -DREQUIRE_FUSE=${require.fuse} -G '${generator}'"/>
+ </exec>
+ <exec executable="msbuild" dir="${project.build.directory}/native"
+ failonerror="true">
+ <arg line="ALL_BUILD.vcxproj /nologo /p:Configuration=RelWithDebInfo /p:LinkIncremental=false"/>
+ </exec>
+ <!-- Copy for inclusion in distribution. -->
+ <copy todir="${project.build.directory}/bin">
+ <fileset dir="${project.build.directory}/native/target/bin/RelWithDebInfo"/>
+ </copy>
+ </target>
+ </configuration>
+ </execution>
+ <execution>
+ <id>native_tests</id>
+ <phase>test</phase>
+ <goals><goal>run</goal></goals>
+ <configuration>
+ <skip>${skipTests}</skip>
+ <target>
+ <property name="compile_classpath" refid="maven.compile.classpath"/>
+ <property name="test_classpath" refid="maven.test.classpath"/>
+ <macrodef name="run-test">
+ <attribute name="test"/>
+ <sequential>
+ <echo message="Running @{test}"/>
+ <exec executable="${project.build.directory}/native/RelWithDebInfo/@{test}" failonerror="true" dir="${project.build.directory}/native/">
+ <env key="CLASSPATH" value="${test_classpath}:${compile_classpath}"/>
+ <!-- HADOOP_HOME required to find winutils. -->
+ <env key="HADOOP_HOME" value="${hadoop.common.build.dir}"/>
+ <!-- Make sure hadoop.dll and jvm.dll are on PATH. -->
+ <env key="PATH" value="${env.PATH};${hadoop.common.build.dir}/bin;${java.home}/jre/bin/server;${java.home}/bin/server"/>
+ </exec>
+ <echo message="Finished @{test}"/>
+ </sequential>
+ </macrodef>
+ <run-test test="test_libhdfs_threaded"/>
+ <echo message="Skipping test_libhdfs_zerocopy"/>
+ <run-test test="test_native_mini_dfs"/>
+ </target>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ <profile>
+ <id>native</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+ <properties>
+ <runningWithNative>true</runningWithNative>
+ </properties>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>make</id>
+ <phase>compile</phase>
+ <goals><goal>run</goal></goals>
+ <configuration>
+ <target>
+ <mkdir dir="${project.build.directory}"/>
+ <exec executable="cmake" dir="${project.build.directory}" failonerror="true">
+ <arg line="${basedir}/src/ -DGENERATED_JAVAH=${project.build.directory}/native/javah -DJVM_ARCH_DATA_MODEL=${sun.arch.data.model} -DREQUIRE_LIBWEBHDFS=${require.libwebhdfs} -DREQUIRE_FUSE=${require.fuse}"/>
+ </exec>
+ <exec executable="make" dir="${project.build.directory}" failonerror="true">
+ </exec>
+ </target>
+ </configuration>
+ </execution>
+ <execution>
+ <id>native_tests</id>
+ <phase>test</phase>
+ <goals><goal>run</goal></goals>
+ <configuration>
+ <skip>${skipTests}</skip>
+ <target>
+ <property name="compile_classpath" refid="maven.compile.classpath"/>
+ <property name="test_classpath" refid="maven.test.classpath"/>
+ <macrodef name="run-test">
+ <attribute name="test"/>
+ <sequential>
+ <echo message="Running @{test} ${compile_classpath} ${test_classpath}"/>
+ <exec executable="${project.build.directory}/main/native/libhdfs/@{test}" failonerror="true" dir="${project.build.directory}/">
+ <env key="CLASSPATH" value="${test_classpath}:${compile_classpath}"/>
+ <!-- Make sure libhadoop.so is on LD_LIBRARY_PATH. -->
+ <env key="LD_LIBRARY_PATH" value="${env.LD_LIBRARY_PATH}:${project.build.directory}/target/usr/local/lib:${hadoop.common.build.dir}/native/target/usr/local/lib"/>
+ </exec>
+ <echo message="Finished @{test}"/>
+ </sequential>
+ </macrodef>
+ <run-test test="test_libhdfs_threaded"/>
+ <run-test test="test_libhdfs_zerocopy"/>
+ <run-test test="test_native_mini_dfs"/>
+ </target>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+</project>
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/CMakeLists.txt b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/CMakeLists.txt
new file mode 100644
index 0000000..9dacec7
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/CMakeLists.txt
@@ -0,0 +1,92 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+#
+
+cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/../../../hadoop-common-project/hadoop-common)
+include(HadoopCommon)
+
+# Check to see if our compiler and linker support the __thread attribute.
+# On Linux and some other operating systems, this is a more efficient
+# alternative to POSIX thread local storage.
+include(CheckCSourceCompiles)
+check_c_source_compiles("int main(void) { static __thread int i = 0; return 0; }" HAVE_BETTER_TLS)
+
+# Check to see if we have Intel SSE intrinsics.
+check_c_source_compiles("#include <emmintrin.h>\nint main(void) { __m128d sum0 = _mm_set_pd(0.0,0.0); return 0; }" HAVE_INTEL_SSE_INTRINSICS)
+
+set(_FUSE_DFS_VERSION 0.1.0)
+configure_file(${CMAKE_SOURCE_DIR}/config.h.cmake ${CMAKE_BINARY_DIR}/config.h)
+
+# Check if we need to link dl library to get dlopen.
+# dlopen on Linux is in separate library but on FreeBSD its in libc
+include(CheckLibraryExists)
+check_library_exists(dl dlopen "" NEED_LINK_DL)
+
+if(WIN32)
+ # Set the optimizer level.
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /O2")
+ # Set warning level 4.
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4")
+ # Skip "unreferenced formal parameter".
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4100")
+ # Skip "conditional expression is constant".
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4127")
+ # Skip deprecated POSIX function warnings.
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_CRT_NONSTDC_NO_DEPRECATE")
+ # Skip CRT non-secure function warnings. If we can convert usage of
+ # strerror, getenv and ctime to their secure CRT equivalents, then we can
+ # re-enable the CRT non-secure function warnings.
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_CRT_SECURE_NO_WARNINGS")
+ # Omit unneeded headers.
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DWIN32_LEAN_AND_MEAN")
+ set(OS_DIR ${CMAKE_SOURCE_DIR}/main/native/libhdfs/os/windows)
+ set(OUT_DIR target/bin)
+else()
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden")
+ set(OS_DIR ${CMAKE_SOURCE_DIR}/main/native/libhdfs/os/posix)
+ set(OUT_DIR target/usr/local/lib)
+endif()
+
+# Configure JNI.
+include(HadoopJNI)
+
+add_subdirectory(main/native/libhdfs)
+
+if(REQUIRE_LIBWEBHDFS)
+ add_subdirectory(contrib/libwebhdfs)
+endif()
+
+# Find Linux FUSE
+if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
+ find_package(PkgConfig REQUIRED)
+ pkg_check_modules(FUSE fuse)
+ if(FUSE_FOUND)
+ add_subdirectory(main/native/fuse-dfs)
+ else()
+ message(STATUS "Failed to find Linux FUSE libraries or include files. Will not build FUSE client.")
+ if(REQUIRE_FUSE)
+ message(FATAL_ERROR "Required component fuse_dfs could not be built.")
+ endif()
+ endif(FUSE_FOUND)
+else()
+ message(STATUS "Non-Linux system detected. Will not build FUSE client.")
+ if(REQUIRE_FUSE)
+ message(FATAL_ERROR "Required component fuse_dfs could not be built.")
+ endif()
+endif()
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/config.h.cmake
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/config.h.cmake b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/config.h.cmake
new file mode 100644
index 0000000..0d11fc4
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/config.h.cmake
@@ -0,0 +1,27 @@
+/**
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you 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.
+*/
+#ifndef CONFIG_H
+#define CONFIG_H
+
+#cmakedefine _FUSE_DFS_VERSION "@_FUSE_DFS_VERSION@"
+
+#cmakedefine HAVE_BETTER_TLS
+
+#cmakedefine HAVE_INTEL_SSE_INTRINSICS
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/CMakeLists.txt b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/CMakeLists.txt
new file mode 100644
index 0000000..009dfd6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/CMakeLists.txt
@@ -0,0 +1,87 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+#
+
+find_package(CURL REQUIRED)
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
+ "${CMAKE_SOURCE_DIR}/contrib/libwebhdfs/resources/")
+
+find_package(Jansson REQUIRED)
+include_directories(
+ ${JNI_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_SOURCE_DIR}/main/native
+ ${CMAKE_SOURCE_DIR}/main/native/libhdfs
+ ${OS_DIR}
+ ${JANSSON_INCLUDE_DIR}
+)
+
+add_definitions(-DLIBHDFS_DLL_EXPORT)
+
+hadoop_add_dual_library(webhdfs
+ src/hdfs_web.c
+ src/hdfs_http_client.c
+ src/hdfs_http_query.c
+ src/hdfs_json_parser.c
+ ../../main/native/libhdfs/exception.c
+ ../../main/native/libhdfs/jni_helper.c
+ ../../main/native/libhdfs/common/htable.c
+ ${OS_DIR}/mutexes.c
+ ${OS_DIR}/thread_local_storage.c
+)
+hadoop_target_link_dual_libraries(webhdfs
+ ${JAVA_JVM_LIBRARY}
+ ${CURL_LIBRARY}
+ ${JANSSON_LIBRARY}
+ pthread
+)
+hadoop_dual_output_directory(webhdfs target)
+set(LIBWEBHDFS_VERSION "0.0.0")
+set_target_properties(webhdfs PROPERTIES
+ SOVERSION ${LIBWEBHDFS_VERSION})
+
+add_executable(test_libwebhdfs_ops
+ src/test_libwebhdfs_ops.c
+)
+target_link_libraries(test_libwebhdfs_ops
+ webhdfs
+ native_mini_dfs
+)
+
+add_executable(test_libwebhdfs_read
+ src/test_libwebhdfs_read.c
+)
+target_link_libraries(test_libwebhdfs_read
+ webhdfs
+)
+
+add_executable(test_libwebhdfs_write
+ src/test_libwebhdfs_write.c
+)
+target_link_libraries(test_libwebhdfs_write
+ webhdfs
+)
+
+add_executable(test_libwebhdfs_threaded
+ src/test_libwebhdfs_threaded.c
+)
+target_link_libraries(test_libwebhdfs_threaded
+ webhdfs
+ native_mini_dfs
+ pthread
+)
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/resources/FindJansson.cmake
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/resources/FindJansson.cmake b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/resources/FindJansson.cmake
new file mode 100644
index 0000000..b8c67ea
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/resources/FindJansson.cmake
@@ -0,0 +1,43 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+
+
+# - Try to find Jansson
+# Once done this will define
+# JANSSON_FOUND - System has Jansson
+# JANSSON_INCLUDE_DIRS - The Jansson include directories
+# JANSSON_LIBRARIES - The libraries needed to use Jansson
+# JANSSON_DEFINITIONS - Compiler switches required for using Jansson
+
+find_path(JANSSON_INCLUDE_DIR jansson.h
+ /usr/include
+ /usr/include/jansson
+ /usr/local/include )
+
+find_library(JANSSON_LIBRARY NAMES jansson
+ PATHS /usr/lib /usr/local/lib )
+
+set(JANSSON_LIBRARIES ${JANSSON_LIBRARY} )
+set(JANSSON_INCLUDE_DIRS ${JANSSON_INCLUDE_DIR} )
+
+include(FindPackageHandleStandardArgs)
+# handle the QUIETLY and REQUIRED arguments and set JANSSON_FOUND to TRUE
+# if all listed variables are TRUE
+find_package_handle_standard_args(Jansson DEFAULT_MSG
+ JANSSON_LIBRARY JANSSON_INCLUDE_DIR)
+
+mark_as_advanced(JANSSON_INCLUDE_DIR JANSSON_LIBRARY )
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_client.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_client.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_client.c
new file mode 100644
index 0000000..dc5ca41
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_client.c
@@ -0,0 +1,490 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <curl/curl.h>
+
+#include "hdfs_http_client.h"
+#include "exception.h"
+
+static pthread_mutex_t curlInitMutex = PTHREAD_MUTEX_INITIALIZER;
+static volatile int curlGlobalInited = 0;
+
+const char *hdfs_strerror(int errnoval)
+{
+#if defined(__sun)
+// MT-Safe under Solaris which doesn't support sys_errlist/sys_nerr
+ return strerror(errnoval);
+#else
+ if ((errnoval < 0) || (errnoval >= sys_nerr)) {
+ return "unknown error.";
+ }
+ return sys_errlist[errnoval];
+#endif
+}
+
+int initResponseBuffer(struct ResponseBuffer **buffer)
+{
+ struct ResponseBuffer *info = NULL;
+ int ret = 0;
+ info = calloc(1, sizeof(struct ResponseBuffer));
+ if (!info) {
+ ret = ENOMEM;
+ }
+ *buffer = info;
+ return ret;
+}
+
+void freeResponseBuffer(struct ResponseBuffer *buffer)
+{
+ if (buffer) {
+ if (buffer->content) {
+ free(buffer->content);
+ }
+ free(buffer);
+ buffer = NULL;
+ }
+}
+
+void freeResponse(struct Response *resp)
+{
+ if (resp) {
+ freeResponseBuffer(resp->body);
+ freeResponseBuffer(resp->header);
+ free(resp);
+ resp = NULL;
+ }
+}
+
+/**
+ * Callback used by libcurl for allocating local buffer and
+ * reading data to local buffer
+ */
+static size_t writefunc(void *ptr, size_t size,
+ size_t nmemb, struct ResponseBuffer *rbuffer)
+{
+ void *temp = NULL;
+ if (size * nmemb < 1) {
+ return 0;
+ }
+ if (!rbuffer) {
+ fprintf(stderr,
+ "ERROR: ResponseBuffer is NULL for the callback writefunc.\n");
+ return 0;
+ }
+
+ if (rbuffer->remaining < size * nmemb) {
+ temp = realloc(rbuffer->content, rbuffer->offset + size * nmemb + 1);
+ if (temp == NULL) {
+ fprintf(stderr, "ERROR: fail to realloc in callback writefunc.\n");
+ return 0;
+ }
+ rbuffer->content = temp;
+ rbuffer->remaining = size * nmemb;
+ }
+ memcpy(rbuffer->content + rbuffer->offset, ptr, size * nmemb);
+ rbuffer->offset += size * nmemb;
+ (rbuffer->content)[rbuffer->offset] = '\0';
+ rbuffer->remaining -= size * nmemb;
+ return size * nmemb;
+}
+
+/**
+ * Callback used by libcurl for reading data into buffer provided by user,
+ * thus no need to reallocate buffer.
+ */
+static size_t writeFuncWithUserBuffer(void *ptr, size_t size,
+ size_t nmemb, struct ResponseBuffer *rbuffer)
+{
+ size_t toCopy = 0;
+ if (size * nmemb < 1) {
+ return 0;
+ }
+ if (!rbuffer || !rbuffer->content) {
+ fprintf(stderr,
+ "ERROR: buffer to read is NULL for the "
+ "callback writeFuncWithUserBuffer.\n");
+ return 0;
+ }
+
+ toCopy = rbuffer->remaining < (size * nmemb) ?
+ rbuffer->remaining : (size * nmemb);
+ memcpy(rbuffer->content + rbuffer->offset, ptr, toCopy);
+ rbuffer->offset += toCopy;
+ rbuffer->remaining -= toCopy;
+ return toCopy;
+}
+
+/**
+ * Callback used by libcurl for writing data to remote peer
+ */
+static size_t readfunc(void *ptr, size_t size, size_t nmemb, void *stream)
+{
+ struct webhdfsBuffer *wbuffer = NULL;
+ if (size * nmemb < 1) {
+ return 0;
+ }
+
+ wbuffer = stream;
+ pthread_mutex_lock(&wbuffer->writeMutex);
+ while (wbuffer->remaining == 0) {
+ /*
+ * The current remainning bytes to write is 0,
+ * check closeFlag to see whether need to finish the transfer.
+ * if yes, return 0; else, wait
+ */
+ if (wbuffer->closeFlag) { // We can close the transfer now
+ //For debug
+ fprintf(stderr, "CloseFlag is set, ready to close the transfer\n");
+ pthread_mutex_unlock(&wbuffer->writeMutex);
+ return 0;
+ } else {
+ // remaining == 0 but closeFlag is not set
+ // indicates that user's buffer has been transferred
+ pthread_cond_signal(&wbuffer->transfer_finish);
+ pthread_cond_wait(&wbuffer->newwrite_or_close,
+ &wbuffer->writeMutex);
+ }
+ }
+
+ if (wbuffer->remaining > 0 && !wbuffer->closeFlag) {
+ size_t copySize = wbuffer->remaining < size * nmemb ?
+ wbuffer->remaining : size * nmemb;
+ memcpy(ptr, wbuffer->wbuffer + wbuffer->offset, copySize);
+ wbuffer->offset += copySize;
+ wbuffer->remaining -= copySize;
+ pthread_mutex_unlock(&wbuffer->writeMutex);
+ return copySize;
+ } else {
+ fprintf(stderr, "ERROR: webhdfsBuffer's remaining is %ld, "
+ "it should be a positive value!\n", wbuffer->remaining);
+ pthread_mutex_unlock(&wbuffer->writeMutex);
+ return 0;
+ }
+}
+
+/**
+ * Initialize the global libcurl environment
+ */
+static void initCurlGlobal()
+{
+ if (!curlGlobalInited) {
+ pthread_mutex_lock(&curlInitMutex);
+ if (!curlGlobalInited) {
+ curl_global_init(CURL_GLOBAL_ALL);
+ curlGlobalInited = 1;
+ }
+ pthread_mutex_unlock(&curlInitMutex);
+ }
+}
+
+/**
+ * Launch simple commands (commands without file I/O) and return response
+ *
+ * @param url Target URL
+ * @param method HTTP method (GET/PUT/POST)
+ * @param followloc Whether or not need to set CURLOPT_FOLLOWLOCATION
+ * @param response Response from remote service
+ * @return 0 for success and non-zero value to indicate error
+ */
+static int launchCmd(const char *url, enum HttpHeader method,
+ enum Redirect followloc, struct Response **response)
+{
+ CURL *curl = NULL;
+ CURLcode curlCode;
+ int ret = 0;
+ struct Response *resp = NULL;
+
+ resp = calloc(1, sizeof(struct Response));
+ if (!resp) {
+ return ENOMEM;
+ }
+ ret = initResponseBuffer(&(resp->body));
+ if (ret) {
+ goto done;
+ }
+ ret = initResponseBuffer(&(resp->header));
+ if (ret) {
+ goto done;
+ }
+ initCurlGlobal();
+ curl = curl_easy_init();
+ if (!curl) {
+ ret = ENOMEM; // curl_easy_init does not return error code,
+ // and most of its errors are caused by malloc()
+ fprintf(stderr, "ERROR in curl_easy_init.\n");
+ goto done;
+ }
+ /* Set callback function for reading data from remote service */
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp->body);
+ curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writefunc);
+ curl_easy_setopt(curl, CURLOPT_WRITEHEADER, resp->header);
+ curl_easy_setopt(curl, CURLOPT_URL, url);
+ switch(method) {
+ case GET:
+ break;
+ case PUT:
+ curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
+ break;
+ case POST:
+ curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
+ break;
+ case DELETE:
+ curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
+ break;
+ default:
+ ret = EINVAL;
+ fprintf(stderr, "ERROR: Invalid HTTP method\n");
+ goto done;
+ }
+ if (followloc == YES) {
+ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
+ }
+ /* Now run the curl handler */
+ curlCode = curl_easy_perform(curl);
+ if (curlCode != CURLE_OK) {
+ ret = EIO;
+ fprintf(stderr, "ERROR: preform the URL %s failed, <%d>: %s\n",
+ url, curlCode, curl_easy_strerror(curlCode));
+ }
+done:
+ if (curl != NULL) {
+ curl_easy_cleanup(curl);
+ }
+ if (ret) {
+ free(resp);
+ resp = NULL;
+ }
+ *response = resp;
+ return ret;
+}
+
+/**
+ * Launch the read request. The request is sent to the NameNode and then
+ * redirected to corresponding DataNode
+ *
+ * @param url The URL for the read request
+ * @param resp The response containing the buffer provided by user
+ * @return 0 for success and non-zero value to indicate error
+ */
+static int launchReadInternal(const char *url, struct Response* resp)
+{
+ CURL *curl;
+ CURLcode curlCode;
+ int ret = 0;
+
+ if (!resp || !resp->body || !resp->body->content) {
+ fprintf(stderr,
+ "ERROR: invalid user-provided buffer!\n");
+ return EINVAL;
+ }
+
+ initCurlGlobal();
+ /* get a curl handle */
+ curl = curl_easy_init();
+ if (!curl) {
+ fprintf(stderr, "ERROR in curl_easy_init.\n");
+ return ENOMEM;
+ }
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFuncWithUserBuffer);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp->body);
+ curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writefunc);
+ curl_easy_setopt(curl, CURLOPT_WRITEHEADER, resp->header);
+ curl_easy_setopt(curl, CURLOPT_URL, url);
+ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
+
+ curlCode = curl_easy_perform(curl);
+ if (curlCode != CURLE_OK && curlCode != CURLE_PARTIAL_FILE) {
+ ret = EIO;
+ fprintf(stderr, "ERROR: preform the URL %s failed, <%d>: %s\n",
+ url, curlCode, curl_easy_strerror(curlCode));
+ }
+
+ curl_easy_cleanup(curl);
+ return ret;
+}
+
+/**
+ * The function does the write operation by connecting to a DataNode.
+ * The function keeps the connection with the DataNode until
+ * the closeFlag is set. Whenever the current data has been sent out,
+ * the function blocks waiting for further input from user or close.
+ *
+ * @param url URL of the remote DataNode
+ * @param method PUT for create and POST for append
+ * @param uploadBuffer Buffer storing user's data to write
+ * @param response Response from remote service
+ * @return 0 for success and non-zero value to indicate error
+ */
+static int launchWrite(const char *url, enum HttpHeader method,
+ struct webhdfsBuffer *uploadBuffer,
+ struct Response **response)
+{
+ CURLcode curlCode;
+ struct Response* resp = NULL;
+ struct curl_slist *chunk = NULL;
+ CURL *curl = NULL;
+ int ret = 0;
+
+ if (!uploadBuffer) {
+ fprintf(stderr, "ERROR: upload buffer is NULL!\n");
+ return EINVAL;
+ }
+
+ initCurlGlobal();
+ resp = calloc(1, sizeof(struct Response));
+ if (!resp) {
+ return ENOMEM;
+ }
+ ret = initResponseBuffer(&(resp->body));
+ if (ret) {
+ goto done;
+ }
+ ret = initResponseBuffer(&(resp->header));
+ if (ret) {
+ goto done;
+ }
+
+ // Connect to the datanode in order to create the lease in the namenode
+ curl = curl_easy_init();
+ if (!curl) {
+ fprintf(stderr, "ERROR: failed to initialize the curl handle.\n");
+ return ENOMEM;
+ }
+ curl_easy_setopt(curl, CURLOPT_URL, url);
+
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp->body);
+ curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writefunc);
+ curl_easy_setopt(curl, CURLOPT_WRITEHEADER, resp->header);
+ curl_easy_setopt(curl, CURLOPT_READFUNCTION, readfunc);
+ curl_easy_setopt(curl, CURLOPT_READDATA, uploadBuffer);
+ curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
+
+ chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked");
+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
+ chunk = curl_slist_append(chunk, "Expect:");
+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
+
+ switch(method) {
+ case PUT:
+ curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
+ break;
+ case POST:
+ curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
+ break;
+ default:
+ ret = EINVAL;
+ fprintf(stderr, "ERROR: Invalid HTTP method\n");
+ goto done;
+ }
+ curlCode = curl_easy_perform(curl);
+ if (curlCode != CURLE_OK) {
+ ret = EIO;
+ fprintf(stderr, "ERROR: preform the URL %s failed, <%d>: %s\n",
+ url, curlCode, curl_easy_strerror(curlCode));
+ }
+
+done:
+ if (chunk != NULL) {
+ curl_slist_free_all(chunk);
+ }
+ if (curl != NULL) {
+ curl_easy_cleanup(curl);
+ }
+ if (ret) {
+ free(resp);
+ resp = NULL;
+ }
+ *response = resp;
+ return ret;
+}
+
+int launchMKDIR(const char *url, struct Response **resp)
+{
+ return launchCmd(url, PUT, NO, resp);
+}
+
+int launchRENAME(const char *url, struct Response **resp)
+{
+ return launchCmd(url, PUT, NO, resp);
+}
+
+int launchGFS(const char *url, struct Response **resp)
+{
+ return launchCmd(url, GET, NO, resp);
+}
+
+int launchLS(const char *url, struct Response **resp)
+{
+ return launchCmd(url, GET, NO, resp);
+}
+
+int launchCHMOD(const char *url, struct Response **resp)
+{
+ return launchCmd(url, PUT, NO, resp);
+}
+
+int launchCHOWN(const char *url, struct Response **resp)
+{
+ return launchCmd(url, PUT, NO, resp);
+}
+
+int launchDELETE(const char *url, struct Response **resp)
+{
+ return launchCmd(url, DELETE, NO, resp);
+}
+
+int launchOPEN(const char *url, struct Response* resp)
+{
+ return launchReadInternal(url, resp);
+}
+
+int launchUTIMES(const char *url, struct Response **resp)
+{
+ return launchCmd(url, PUT, NO, resp);
+}
+
+int launchNnWRITE(const char *url, struct Response **resp)
+{
+ return launchCmd(url, PUT, NO, resp);
+}
+
+int launchNnAPPEND(const char *url, struct Response **resp)
+{
+ return launchCmd(url, POST, NO, resp);
+}
+
+int launchDnWRITE(const char *url, struct webhdfsBuffer *buffer,
+ struct Response **resp)
+{
+ return launchWrite(url, PUT, buffer, resp);
+}
+
+int launchDnAPPEND(const char *url, struct webhdfsBuffer *buffer,
+ struct Response **resp)
+{
+ return launchWrite(url, POST, buffer, resp);
+}
+
+int launchSETREPLICATION(const char *url, struct Response **resp)
+{
+ return launchCmd(url, PUT, NO, resp);
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_client.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_client.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_client.h
new file mode 100644
index 0000000..8d1c3db
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_client.h
@@ -0,0 +1,294 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+
+
+#ifndef _HDFS_HTTP_CLIENT_H_
+#define _HDFS_HTTP_CLIENT_H_
+
+#include "hdfs.h" /* for tSize */
+
+#include <pthread.h> /* for pthread_t */
+#include <unistd.h> /* for size_t */
+
+/** enum indicating the type of hdfs stream */
+enum hdfsStreamType
+{
+ UNINITIALIZED = 0,
+ INPUT = 1,
+ OUTPUT = 2,
+};
+
+/**
+ * webhdfsBuffer - used for hold the data for read/write from/to http connection
+ */
+struct webhdfsBuffer {
+ const char *wbuffer; /* The user's buffer for uploading */
+ size_t remaining; /* Length of content */
+ size_t offset; /* offset for reading */
+ /* Check whether the hdfsOpenFile has been called before */
+ int openFlag;
+ /* Whether to close the http connection for writing */
+ int closeFlag;
+ /* Synchronization between the curl and hdfsWrite threads */
+ pthread_mutex_t writeMutex;
+ /*
+ * Transferring thread waits for this condition
+ * when there is no more content for transferring in the buffer
+ */
+ pthread_cond_t newwrite_or_close;
+ /* Condition used to indicate finishing transferring (one buffer) */
+ pthread_cond_t transfer_finish;
+};
+
+/** File handle for webhdfs */
+struct webhdfsFileHandle {
+ char *absPath; /* Absolute path of file */
+ int bufferSize; /* Size of buffer */
+ short replication; /* Number of replication */
+ tSize blockSize; /* Block size */
+ char *datanode; /* URL of the DataNode */
+ /* webhdfsBuffer handle used to store the upload data */
+ struct webhdfsBuffer *uploadBuffer;
+ /* The thread used for data transferring */
+ pthread_t connThread;
+};
+
+/** Type of http header */
+enum HttpHeader {
+ GET,
+ PUT,
+ POST,
+ DELETE
+};
+
+/** Whether to redirect */
+enum Redirect {
+ YES,
+ NO
+};
+
+/** Buffer used for holding response */
+struct ResponseBuffer {
+ char *content;
+ size_t remaining;
+ size_t offset;
+};
+
+/**
+ * The response got through webhdfs
+ */
+struct Response {
+ struct ResponseBuffer *body;
+ struct ResponseBuffer *header;
+};
+
+/**
+ * Create and initialize a ResponseBuffer
+ *
+ * @param buffer Pointer pointing to new created ResponseBuffer handle
+ * @return 0 for success, non-zero value to indicate error
+ */
+int initResponseBuffer(struct ResponseBuffer **buffer) __attribute__ ((warn_unused_result));
+
+/**
+ * Free the given ResponseBuffer
+ *
+ * @param buffer The ResponseBuffer to free
+ */
+void freeResponseBuffer(struct ResponseBuffer *buffer);
+
+/**
+ * Free the given Response
+ *
+ * @param resp The Response to free
+ */
+void freeResponse(struct Response *resp);
+
+/**
+ * Send the MKDIR request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for MKDIR operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchMKDIR(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the RENAME request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for RENAME operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchRENAME(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the CHMOD request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for CHMOD operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchCHMOD(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the GetFileStatus request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for GetFileStatus operation
+ * @param response Response handle to store response returned from the NameNode,
+ * containing either file status or exception information
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchGFS(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the LS (LISTSTATUS) request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for LISTSTATUS operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchLS(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the DELETE request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for DELETE operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchDELETE(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the CHOWN request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for CHOWN operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchCHOWN(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the OPEN request to NameNode using the given URL,
+ * asking for reading a file (within a range).
+ * The NameNode first redirects the request to the datanode
+ * that holds the corresponding first block of the file (within a range),
+ * and the datanode returns the content of the file through the HTTP connection.
+ *
+ * @param url The URL for OPEN operation
+ * @param resp The response holding user's buffer.
+ The file content will be written into the buffer.
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchOPEN(const char *url,
+ struct Response* resp) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the SETTIMES request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for SETTIMES operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchUTIMES(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the WRITE/CREATE request to NameNode using the given URL.
+ * The NameNode will choose the writing target datanodes
+ * and return the first datanode in the pipeline as response
+ *
+ * @param url The URL for WRITE/CREATE operation connecting to NameNode
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchNnWRITE(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the WRITE request along with to-write content to
+ * the corresponding DataNode using the given URL.
+ * The DataNode will write the data and return the response.
+ *
+ * @param url The URL for WRITE operation connecting to DataNode
+ * @param buffer The webhdfsBuffer containing data to be written to hdfs
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchDnWRITE(const char *url, struct webhdfsBuffer *buffer,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the WRITE (APPEND) request to NameNode using the given URL.
+ * The NameNode determines the DataNode for appending and
+ * sends its URL back as response.
+ *
+ * @param url The URL for APPEND operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchNnAPPEND(const char *url, struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the SETREPLICATION request to NameNode using the given URL.
+ * The NameNode will execute the operation and return the result as response.
+ *
+ * @param url The URL for SETREPLICATION operation
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchSETREPLICATION(const char *url,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Send the APPEND request along with the content to DataNode.
+ * The DataNode will do the appending and return the result as response.
+ *
+ * @param url The URL for APPEND operation connecting to DataNode
+ * @param buffer The webhdfsBuffer containing data to be appended
+ * @param response Response handle to store response returned from the NameNode
+ * @return 0 for success, non-zero value to indicate error
+ */
+int launchDnAPPEND(const char *url, struct webhdfsBuffer *buffer,
+ struct Response **response) __attribute__ ((warn_unused_result));
+
+/**
+ * Thread-safe strerror alternative.
+ *
+ * @param errnoval The error code value
+ * @return The error message string mapped to the given error code
+ */
+const char *hdfs_strerror(int errnoval);
+
+#endif //_HDFS_HTTP_CLIENT_H_
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_query.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_query.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_query.c
new file mode 100644
index 0000000..b082c08
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_query.c
@@ -0,0 +1,402 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+#include "hdfs_http_query.h"
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+
+#define PERM_STR_LEN 4 // "644" + one byte for NUL
+#define SHORT_STR_LEN 6 // 65535 + NUL
+#define LONG_STR_LEN 21 // 2^64-1 = 18446744073709551615 + NUL
+
+/**
+ * Create query based on NameNode hostname,
+ * NameNode port, path, operation and other parameters
+ *
+ * @param host NameNode hostName
+ * @param nnPort Port of NameNode
+ * @param path Absolute path for the corresponding file
+ * @param op Operations
+ * @param paraNum Number of remaining parameters
+ * @param paraNames Names of remaining parameters
+ * @param paraValues Values of remaining parameters
+ * @param url Holding the created URL
+ * @return 0 on success and non-zero value to indicate error
+ */
+static int createQueryURL(const char *host, unsigned int nnPort,
+ const char *path, const char *op, int paraNum,
+ const char **paraNames, const char **paraValues,
+ char **queryUrl)
+{
+ size_t length = 0;
+ int i = 0, offset = 0, ret = 0;
+ char *url = NULL;
+ const char *protocol = "http://";
+ const char *prefix = "/webhdfs/v1";
+
+ if (!paraNames || !paraValues) {
+ return EINVAL;
+ }
+ length = strlen(protocol) + strlen(host) + strlen(":") +
+ SHORT_STR_LEN + strlen(prefix) + strlen(path) +
+ strlen ("?op=") + strlen(op);
+ for (i = 0; i < paraNum; i++) {
+ if (paraNames[i] && paraValues[i]) {
+ length += 2 + strlen(paraNames[i]) + strlen(paraValues[i]);
+ }
+ }
+ url = malloc(length); // The '\0' has already been included
+ // when using SHORT_STR_LEN
+ if (!url) {
+ return ENOMEM;
+ }
+
+ offset = snprintf(url, length, "%s%s:%d%s%s?op=%s",
+ protocol, host, nnPort, prefix, path, op);
+ if (offset >= length || offset < 0) {
+ ret = EIO;
+ goto done;
+ }
+ for (i = 0; i < paraNum; i++) {
+ if (!paraNames[i] || !paraValues[i] || paraNames[i][0] == '\0' ||
+ paraValues[i][0] == '\0') {
+ continue;
+ }
+ offset += snprintf(url + offset, length - offset,
+ "&%s=%s", paraNames[i], paraValues[i]);
+ if (offset >= length || offset < 0) {
+ ret = EIO;
+ goto done;
+ }
+ }
+done:
+ if (ret) {
+ free(url);
+ return ret;
+ }
+ *queryUrl = url;
+ return 0;
+}
+
+int createUrlForMKDIR(const char *host, int nnPort,
+ const char *path, const char *user, char **url)
+{
+ const char *userPara = "user.name";
+ return createQueryURL(host, nnPort, path, "MKDIRS", 1,
+ &userPara, &user, url);
+}
+
+int createUrlForGetFileStatus(const char *host, int nnPort, const char *path,
+ const char *user, char **url)
+{
+ const char *userPara = "user.name";
+ return createQueryURL(host, nnPort, path, "GETFILESTATUS", 1,
+ &userPara, &user, url);
+}
+
+int createUrlForLS(const char *host, int nnPort, const char *path,
+ const char *user, char **url)
+{
+ const char *userPara = "user.name";
+ return createQueryURL(host, nnPort, path, "LISTSTATUS",
+ 1, &userPara, &user, url);
+}
+
+int createUrlForNnAPPEND(const char *host, int nnPort, const char *path,
+ const char *user, char **url)
+{
+ const char *userPara = "user.name";
+ return createQueryURL(host, nnPort, path, "APPEND",
+ 1, &userPara, &user, url);
+}
+
+int createUrlForMKDIRwithMode(const char *host, int nnPort, const char *path,
+ int mode, const char *user, char **url)
+{
+ int strlength;
+ char permission[PERM_STR_LEN];
+ const char *paraNames[2], *paraValues[2];
+
+ paraNames[0] = "permission";
+ paraNames[1] = "user.name";
+ memset(permission, 0, PERM_STR_LEN);
+ strlength = snprintf(permission, PERM_STR_LEN, "%o", mode);
+ if (strlength < 0 || strlength >= PERM_STR_LEN) {
+ return EIO;
+ }
+ paraValues[0] = permission;
+ paraValues[1] = user;
+
+ return createQueryURL(host, nnPort, path, "MKDIRS", 2,
+ paraNames, paraValues, url);
+}
+
+int createUrlForRENAME(const char *host, int nnPort, const char *srcpath,
+ const char *destpath, const char *user, char **url)
+{
+ const char *paraNames[2], *paraValues[2];
+ paraNames[0] = "destination";
+ paraNames[1] = "user.name";
+ paraValues[0] = destpath;
+ paraValues[1] = user;
+
+ return createQueryURL(host, nnPort, srcpath,
+ "RENAME", 2, paraNames, paraValues, url);
+}
+
+int createUrlForCHMOD(const char *host, int nnPort, const char *path,
+ int mode, const char *user, char **url)
+{
+ int strlength;
+ char permission[PERM_STR_LEN];
+ const char *paraNames[2], *paraValues[2];
+
+ paraNames[0] = "permission";
+ paraNames[1] = "user.name";
+ memset(permission, 0, PERM_STR_LEN);
+ strlength = snprintf(permission, PERM_STR_LEN, "%o", mode);
+ if (strlength < 0 || strlength >= PERM_STR_LEN) {
+ return EIO;
+ }
+ paraValues[0] = permission;
+ paraValues[1] = user;
+
+ return createQueryURL(host, nnPort, path, "SETPERMISSION",
+ 2, paraNames, paraValues, url);
+}
+
+int createUrlForDELETE(const char *host, int nnPort, const char *path,
+ int recursive, const char *user, char **url)
+{
+ const char *paraNames[2], *paraValues[2];
+ paraNames[0] = "recursive";
+ paraNames[1] = "user.name";
+ if (recursive) {
+ paraValues[0] = "true";
+ } else {
+ paraValues[0] = "false";
+ }
+ paraValues[1] = user;
+
+ return createQueryURL(host, nnPort, path, "DELETE",
+ 2, paraNames, paraValues, url);
+}
+
+int createUrlForCHOWN(const char *host, int nnPort, const char *path,
+ const char *owner, const char *group,
+ const char *user, char **url)
+{
+ const char *paraNames[3], *paraValues[3];
+ paraNames[0] = "owner";
+ paraNames[1] = "group";
+ paraNames[2] = "user.name";
+ paraValues[0] = owner;
+ paraValues[1] = group;
+ paraValues[2] = user;
+
+ return createQueryURL(host, nnPort, path, "SETOWNER",
+ 3, paraNames, paraValues, url);
+}
+
+int createUrlForOPEN(const char *host, int nnPort, const char *path,
+ const char *user, size_t offset, size_t length, char **url)
+{
+ int strlength;
+ char offsetStr[LONG_STR_LEN], lengthStr[LONG_STR_LEN];
+ const char *paraNames[3], *paraValues[3];
+
+ paraNames[0] = "offset";
+ paraNames[1] = "length";
+ paraNames[2] = "user.name";
+ memset(offsetStr, 0, LONG_STR_LEN);
+ memset(lengthStr, 0, LONG_STR_LEN);
+ strlength = snprintf(offsetStr, LONG_STR_LEN, "%lu", offset);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ strlength = snprintf(lengthStr, LONG_STR_LEN, "%lu", length);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ paraValues[0] = offsetStr;
+ paraValues[1] = lengthStr;
+ paraValues[2] = user;
+
+ return createQueryURL(host, nnPort, path, "OPEN",
+ 3, paraNames, paraValues, url);
+}
+
+int createUrlForUTIMES(const char *host, int nnPort, const char *path,
+ long unsigned mTime, long unsigned aTime,
+ const char *user, char **url)
+{
+ int strlength;
+ char modTime[LONG_STR_LEN], acsTime[LONG_STR_LEN];
+ const char *paraNames[3], *paraValues[3];
+
+ memset(modTime, 0, LONG_STR_LEN);
+ memset(acsTime, 0, LONG_STR_LEN);
+ strlength = snprintf(modTime, LONG_STR_LEN, "%lu", mTime);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ strlength = snprintf(acsTime, LONG_STR_LEN, "%lu", aTime);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ paraNames[0] = "modificationtime";
+ paraNames[1] = "accesstime";
+ paraNames[2] = "user.name";
+ paraValues[0] = modTime;
+ paraValues[1] = acsTime;
+ paraValues[2] = user;
+
+ return createQueryURL(host, nnPort, path, "SETTIMES",
+ 3, paraNames, paraValues, url);
+}
+
+int createUrlForNnWRITE(const char *host, int nnPort,
+ const char *path, const char *user,
+ int16_t replication, size_t blockSize, char **url)
+{
+ int strlength;
+ char repStr[SHORT_STR_LEN], blockSizeStr[LONG_STR_LEN];
+ const char *paraNames[4], *paraValues[4];
+
+ memset(repStr, 0, SHORT_STR_LEN);
+ memset(blockSizeStr, 0, LONG_STR_LEN);
+ if (replication > 0) {
+ strlength = snprintf(repStr, SHORT_STR_LEN, "%u", replication);
+ if (strlength < 0 || strlength >= SHORT_STR_LEN) {
+ return EIO;
+ }
+ }
+ if (blockSize > 0) {
+ strlength = snprintf(blockSizeStr, LONG_STR_LEN, "%lu", blockSize);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ }
+ paraNames[0] = "overwrite";
+ paraNames[1] = "replication";
+ paraNames[2] = "blocksize";
+ paraNames[3] = "user.name";
+ paraValues[0] = "true";
+ paraValues[1] = repStr;
+ paraValues[2] = blockSizeStr;
+ paraValues[3] = user;
+
+ return createQueryURL(host, nnPort, path, "CREATE",
+ 4, paraNames, paraValues, url);
+}
+
+int createUrlForSETREPLICATION(const char *host, int nnPort,
+ const char *path, int16_t replication,
+ const char *user, char **url)
+{
+ char repStr[SHORT_STR_LEN];
+ const char *paraNames[2], *paraValues[2];
+ int strlength;
+
+ memset(repStr, 0, SHORT_STR_LEN);
+ if (replication > 0) {
+ strlength = snprintf(repStr, SHORT_STR_LEN, "%u", replication);
+ if (strlength < 0 || strlength >= SHORT_STR_LEN) {
+ return EIO;
+ }
+ }
+ paraNames[0] = "replication";
+ paraNames[1] = "user.name";
+ paraValues[0] = repStr;
+ paraValues[1] = user;
+
+ return createQueryURL(host, nnPort, path, "SETREPLICATION",
+ 2, paraNames, paraValues, url);
+}
+
+int createUrlForGetBlockLocations(const char *host, int nnPort,
+ const char *path, size_t offset,
+ size_t length, const char *user, char **url)
+{
+ char offsetStr[LONG_STR_LEN], lengthStr[LONG_STR_LEN];
+ const char *paraNames[3], *paraValues[3];
+ int strlength;
+
+ memset(offsetStr, 0, LONG_STR_LEN);
+ memset(lengthStr, 0, LONG_STR_LEN);
+ if (offset > 0) {
+ strlength = snprintf(offsetStr, LONG_STR_LEN, "%lu", offset);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ }
+ if (length > 0) {
+ strlength = snprintf(lengthStr, LONG_STR_LEN, "%lu", length);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ }
+ paraNames[0] = "offset";
+ paraNames[1] = "length";
+ paraNames[2] = "user.name";
+ paraValues[0] = offsetStr;
+ paraValues[1] = lengthStr;
+ paraValues[2] = user;
+
+ return createQueryURL(host, nnPort, path, "GET_BLOCK_LOCATIONS",
+ 3, paraNames, paraValues, url);
+}
+
+int createUrlForReadFromDatanode(const char *dnHost, int dnPort,
+ const char *path, size_t offset,
+ size_t length, const char *user,
+ const char *namenodeRpcAddr, char **url)
+{
+ char offsetStr[LONG_STR_LEN], lengthStr[LONG_STR_LEN];
+ const char *paraNames[4], *paraValues[4];
+ int strlength;
+
+ memset(offsetStr, 0, LONG_STR_LEN);
+ memset(lengthStr, 0, LONG_STR_LEN);
+ if (offset > 0) {
+ strlength = snprintf(offsetStr, LONG_STR_LEN, "%lu", offset);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ }
+ if (length > 0) {
+ strlength = snprintf(lengthStr, LONG_STR_LEN, "%lu", length);
+ if (strlength < 0 || strlength >= LONG_STR_LEN) {
+ return EIO;
+ }
+ }
+
+ paraNames[0] = "offset";
+ paraNames[1] = "length";
+ paraNames[2] = "user.name";
+ paraNames[3] = "namenoderpcaddress";
+ paraValues[0] = offsetStr;
+ paraValues[1] = lengthStr;
+ paraValues[2] = user;
+ paraValues[3] = namenodeRpcAddr;
+
+ return createQueryURL(dnHost, dnPort, path, "OPEN",
+ 4, paraNames, paraValues, url);
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_query.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_query.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_query.h
new file mode 100644
index 0000000..432797b
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_http_query.h
@@ -0,0 +1,240 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+
+#ifndef _HDFS_HTTP_QUERY_H_
+#define _HDFS_HTTP_QUERY_H_
+
+#include <unistd.h> /* for size_t */
+#include <inttypes.h> /* for int16_t */
+
+/**
+ * Create the URL for a MKDIR request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the dir to create
+ * @param user User name
+ * @param url Holding the generated URL for MKDIR request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForMKDIR(const char *host, int nnPort,
+ const char *path, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a MKDIR (with mode) request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the dir to create
+ * @param mode Mode of MKDIR
+ * @param user User name
+ * @param url Holding the generated URL for MKDIR request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForMKDIRwithMode(const char *host, int nnPort, const char *path,
+ int mode, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a RENAME request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param srcpath Source path
+ * @param dstpath Destination path
+ * @param user User name
+ * @param url Holding the generated URL for RENAME request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForRENAME(const char *host, int nnPort, const char *srcpath,
+ const char *dstpath, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a CHMOD request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Target path
+ * @param mode New mode for the file
+ * @param user User name
+ * @param url Holding the generated URL for CHMOD request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForCHMOD(const char *host, int nnPort, const char *path,
+ int mode, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a GETFILESTATUS request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the target file
+ * @param user User name
+ * @param url Holding the generated URL for GETFILESTATUS request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForGetFileStatus(const char *host, int nnPort,
+ const char *path, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a LISTSTATUS request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the directory for listing
+ * @param user User name
+ * @param url Holding the generated URL for LISTSTATUS request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForLS(const char *host, int nnPort,
+ const char *path, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a DELETE request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the file to be deletected
+ * @param recursive Whether or not to delete in a recursive way
+ * @param user User name
+ * @param url Holding the generated URL for DELETE request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForDELETE(const char *host, int nnPort, const char *path,
+ int recursive, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a CHOWN request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the target
+ * @param owner New owner
+ * @param group New group
+ * @param user User name
+ * @param url Holding the generated URL for CHOWN request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForCHOWN(const char *host, int nnPort, const char *path,
+ const char *owner, const char *group, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a OPEN/READ request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the file to read
+ * @param user User name
+ * @param offset Offset for reading (the start position for this read)
+ * @param length Length of the file to read
+ * @param url Holding the generated URL for OPEN/READ request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForOPEN(const char *host, int nnPort, const char *path,
+ const char *user, size_t offset, size_t length,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a UTIMES (update time) request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the file for updating time
+ * @param mTime Modified time to set
+ * @param aTime Access time to set
+ * @param user User name
+ * @param url Holding the generated URL for UTIMES request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForUTIMES(const char *host, int nnPort, const char *path,
+ long unsigned mTime, long unsigned aTime,
+ const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a WRITE/CREATE request (sent to NameNode)
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the dir to create
+ * @param user User name
+ * @param replication Number of replication of the file
+ * @param blockSize Size of the block for the file
+ * @param url Holding the generated URL for WRITE request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForNnWRITE(const char *host, int nnPort, const char *path,
+ const char *user, int16_t replication, size_t blockSize,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for an APPEND request (sent to NameNode)
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the file for appending
+ * @param user User name
+ * @param url Holding the generated URL for APPEND request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForNnAPPEND(const char *host, int nnPort,
+ const char *path, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a SETREPLICATION request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the target file
+ * @param replication New replication number
+ * @param user User name
+ * @param url Holding the generated URL for SETREPLICATION request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForSETREPLICATION(const char *host, int nnPort, const char *path,
+ int16_t replication, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+/**
+ * Create the URL for a GET_BLOCK_LOCATIONS request
+ *
+ * @param host The hostname of the NameNode
+ * @param nnPort Port of the NameNode
+ * @param path Path of the target file
+ * @param offset The offset in the file
+ * @param length Length of the file content
+ * @param user User name
+ * @param url Holding the generated URL for GET_BLOCK_LOCATIONS request
+ * @return 0 on success and non-zero value on errors
+ */
+int createUrlForGetBlockLocations(const char *host, int nnPort,
+ const char *path, size_t offset,
+ size_t length, const char *user,
+ char **url) __attribute__ ((warn_unused_result));
+
+
+#endif //_HDFS_HTTP_QUERY_H_
[34/35] hadoop git commit: HDFS-9204.
DatanodeDescriptor#PendingReplicationWithoutTargets is wrongly calculated.
Contributed by Mingliang Liu.
Posted by ji...@apache.org.
HDFS-9204. DatanodeDescriptor#PendingReplicationWithoutTargets is wrongly calculated. Contributed by Mingliang Liu.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/118a35bc
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/118a35bc
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/118a35bc
Branch: refs/heads/HDFS-8966
Commit: 118a35bc2eabe3918b4797a1b626e9a39d77754b
Parents: 0841940
Author: Jing Zhao <ji...@apache.org>
Authored: Thu Oct 8 14:11:02 2015 -0700
Committer: Jing Zhao <ji...@apache.org>
Committed: Thu Oct 8 14:11:02 2015 -0700
----------------------------------------------------------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +++
.../hdfs/server/blockmanagement/DatanodeDescriptor.java | 8 ++++----
.../hadoop/hdfs/server/blockmanagement/ReplicationWork.java | 3 +++
.../server/blockmanagement/TestUnderReplicatedBlocks.java | 5 +++++
4 files changed, 15 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/118a35bc/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 1116f80..95351a2 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -356,6 +356,9 @@ Trunk (Unreleased)
HDFS-8800. hdfs --daemon stop namenode corrupts logs (John Smith via aw)
+ HDFS-9204. DatanodeDescriptor#PendingReplicationWithoutTargets is wrongly
+ calculated. (Mingliang Liu via jing9)
+
BREAKDOWN OF HDFS-7285 SUBTASKS AND RELATED JIRAS
HDFS-7347. Configurable erasure coding policy for individual files and
http://git-wip-us.apache.org/repos/asf/hadoop/blob/118a35bc/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeDescriptor.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeDescriptor.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeDescriptor.java
index b258f06..fde645e 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeDescriptor.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeDescriptor.java
@@ -256,7 +256,7 @@ public class DatanodeDescriptor extends DatanodeInfo {
private boolean disallowed = false;
// The number of replication work pending before targets are determined
- private int PendingReplicationWithoutTargets = 0;
+ private int pendingReplicationWithoutTargets = 0;
// HB processing can use it to tell if it is the first HB since DN restarted
private boolean heartbeatedSinceRegistration = false;
@@ -594,11 +594,11 @@ public class DatanodeDescriptor extends DatanodeInfo {
}
void incrementPendingReplicationWithoutTargets() {
- PendingReplicationWithoutTargets++;
+ pendingReplicationWithoutTargets++;
}
void decrementPendingReplicationWithoutTargets() {
- PendingReplicationWithoutTargets--;
+ pendingReplicationWithoutTargets--;
}
/**
@@ -651,7 +651,7 @@ public class DatanodeDescriptor extends DatanodeInfo {
* The number of work items that are pending to be replicated
*/
int getNumberOfBlocksToBeReplicated() {
- return PendingReplicationWithoutTargets + replicateBlocks.size();
+ return pendingReplicationWithoutTargets + replicateBlocks.size();
}
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/118a35bc/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java
index 8266f45..8a3900c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java
@@ -30,6 +30,9 @@ class ReplicationWork extends BlockRecoveryWork {
int priority) {
super(block, bc, srcNodes, containingNodes,
liveReplicaStorages, additionalReplRequired, priority);
+ assert getSrcNodes().length == 1 :
+ "There should be exactly 1 source node that have been selected";
+ getSrcNodes()[0].incrementPendingReplicationWithoutTargets();
BlockManager.LOG.debug("Creating a ReplicationWork to recover " + block);
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/118a35bc/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlocks.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlocks.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlocks.java
index 27b35f0..c0b54b0 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlocks.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlocks.java
@@ -31,6 +31,7 @@ import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.junit.Test;
+import org.mockito.internal.util.reflection.Whitebox;
import java.util.Iterator;
@@ -135,6 +136,10 @@ public class TestUnderReplicatedBlocks {
assertEquals(NUM_OF_BLOCKS, bm.getUnderReplicatedNotMissingBlocks());
bm.computeDatanodeWork();
+ assertTrue("The number of replication work pending before targets are " +
+ "determined should be non-negative.",
+ (Integer)Whitebox.getInternalState(secondDn,
+ "pendingReplicationWithoutTargets") >= 0);
assertTrue("The number of blocks to be replicated should be less than "
+ "or equal to " + bm.replicationStreamsHardLimit,
[30/35] hadoop git commit: HDFS-8632. Add InterfaceAudience
annotation to the erasure coding classes. Contributed by Rakesh R.
Posted by ji...@apache.org.
HDFS-8632. Add InterfaceAudience annotation to the erasure coding classes. Contributed by Rakesh R.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/66e2cfa1
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/66e2cfa1
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/66e2cfa1
Branch: refs/heads/HDFS-8966
Commit: 66e2cfa1a0285f2b4f62a4ffb4d5c1ee54f76156
Parents: fde729f
Author: Andrew Wang <wa...@apache.org>
Authored: Wed Oct 7 18:12:26 2015 -0700
Committer: Andrew Wang <wa...@apache.org>
Committed: Wed Oct 7 18:12:26 2015 -0700
----------------------------------------------------------------------
.../main/java/org/apache/hadoop/io/erasurecode/CodecUtil.java | 2 ++
.../src/main/java/org/apache/hadoop/io/erasurecode/ECBlock.java | 3 +++
.../java/org/apache/hadoop/io/erasurecode/ECBlockGroup.java | 3 +++
.../src/main/java/org/apache/hadoop/io/erasurecode/ECChunk.java | 3 +++
.../main/java/org/apache/hadoop/io/erasurecode/ECSchema.java | 5 +++++
.../hadoop/io/erasurecode/codec/AbstractErasureCodec.java | 2 ++
.../org/apache/hadoop/io/erasurecode/codec/ErasureCodec.java | 2 ++
.../org/apache/hadoop/io/erasurecode/codec/RSErasureCodec.java | 2 ++
.../org/apache/hadoop/io/erasurecode/codec/XORErasureCodec.java | 2 ++
.../hadoop/io/erasurecode/coder/AbstractErasureCoder.java | 2 ++
.../hadoop/io/erasurecode/coder/AbstractErasureCodingStep.java | 2 ++
.../hadoop/io/erasurecode/coder/AbstractErasureDecoder.java | 2 ++
.../hadoop/io/erasurecode/coder/AbstractErasureEncoder.java | 2 ++
.../org/apache/hadoop/io/erasurecode/coder/ErasureCoder.java | 2 ++
.../apache/hadoop/io/erasurecode/coder/ErasureCodingStep.java | 2 ++
.../apache/hadoop/io/erasurecode/coder/ErasureDecodingStep.java | 2 ++
.../apache/hadoop/io/erasurecode/coder/ErasureEncodingStep.java | 2 ++
.../apache/hadoop/io/erasurecode/coder/RSErasureDecoder.java | 2 ++
.../apache/hadoop/io/erasurecode/coder/RSErasureEncoder.java | 2 ++
.../apache/hadoop/io/erasurecode/coder/XORErasureDecoder.java | 2 ++
.../apache/hadoop/io/erasurecode/coder/XORErasureEncoder.java | 2 ++
.../org/apache/hadoop/io/erasurecode/grouper/BlockGrouper.java | 2 ++
.../hadoop/io/erasurecode/rawcoder/AbstractRawErasureCoder.java | 3 ++-
.../io/erasurecode/rawcoder/AbstractRawErasureDecoder.java | 2 ++
.../io/erasurecode/rawcoder/AbstractRawErasureEncoder.java | 2 ++
.../org/apache/hadoop/io/erasurecode/rawcoder/RSRawDecoder.java | 2 ++
.../org/apache/hadoop/io/erasurecode/rawcoder/RSRawEncoder.java | 2 ++
.../io/erasurecode/rawcoder/RSRawErasureCoderFactory.java | 3 +++
.../apache/hadoop/io/erasurecode/rawcoder/RawErasureCoder.java | 2 ++
.../hadoop/io/erasurecode/rawcoder/RawErasureCoderFactory.java | 3 +++
.../hadoop/io/erasurecode/rawcoder/RawErasureDecoder.java | 2 ++
.../hadoop/io/erasurecode/rawcoder/RawErasureEncoder.java | 2 ++
.../apache/hadoop/io/erasurecode/rawcoder/XORRawDecoder.java | 3 +++
.../apache/hadoop/io/erasurecode/rawcoder/XORRawEncoder.java | 3 +++
.../io/erasurecode/rawcoder/XORRawErasureCoderFactory.java | 3 +++
.../apache/hadoop/io/erasurecode/rawcoder/util/DumpUtil.java | 2 ++
.../apache/hadoop/io/erasurecode/rawcoder/util/GaloisField.java | 3 +++
.../org/apache/hadoop/io/erasurecode/rawcoder/util/RSUtil.java | 3 +++
.../main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java | 2 ++
.../main/java/org/apache/hadoop/hdfs/StripedDataStreamer.java | 2 ++
.../org/apache/hadoop/hdfs/protocol/ErasureCodingPolicy.java | 4 ++++
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +++
.../hadoop/hdfs/server/blockmanagement/BlockInfoStriped.java | 2 ++
.../hdfs/server/blockmanagement/BlockPlacementPolicies.java | 2 ++
.../hdfs/server/datanode/erasurecode/ErasureCodingWorker.java | 2 ++
.../java/org/apache/hadoop/hdfs/tools/erasurecode/ECCli.java | 2 ++
46 files changed, 108 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/CodecUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/CodecUtil.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/CodecUtil.java
index 027d58b..87bedf8 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/CodecUtil.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/CodecUtil.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.io.erasurecode.rawcoder.*;
@@ -24,6 +25,7 @@ import org.apache.hadoop.io.erasurecode.rawcoder.*;
/**
* A codec & coder utility to help create raw coders conveniently.
*/
+@InterfaceAudience.Private
public final class CodecUtil {
private CodecUtil() { }
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlock.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlock.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlock.java
index 5c0a160..a3f24c8 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlock.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlock.java
@@ -17,12 +17,15 @@
*/
package org.apache.hadoop.io.erasurecode;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* A wrapper of block level data source/output that {@link ECChunk}s can be
* extracted from. For HDFS, it can be an HDFS block (250MB). Note it only cares
* about erasure coding specific logic thus avoids coupling with any HDFS block
* details. We can have something like HdfsBlock extend it.
*/
+@InterfaceAudience.Private
public class ECBlock {
private boolean isParity;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlockGroup.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlockGroup.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlockGroup.java
index 91e4fb8..c52d947 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlockGroup.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlockGroup.java
@@ -17,9 +17,12 @@
*/
package org.apache.hadoop.io.erasurecode;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* A group of blocks or {@link ECBlock} incurred in an erasure coding task.
*/
+@InterfaceAudience.Private
public class ECBlockGroup {
private ECBlock[] dataBlocks;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECChunk.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECChunk.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECChunk.java
index d0120d8..cd7c6be 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECChunk.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECChunk.java
@@ -19,9 +19,12 @@ package org.apache.hadoop.io.erasurecode;
import java.nio.ByteBuffer;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* A wrapper for ByteBuffer or bytes array for an erasure code chunk.
*/
+@InterfaceAudience.Private
public class ECChunk {
private ByteBuffer chunkBuffer;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECSchema.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECSchema.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECSchema.java
index 0d5bf8f..1be653b 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECSchema.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECSchema.java
@@ -21,9 +21,14 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+
/**
* Erasure coding schema to housekeeper relevant information.
*/
+@InterfaceAudience.Public
+@InterfaceStability.Evolving
public final class ECSchema {
public static final String NUM_DATA_UNITS_KEY = "numDataUnits";
public static final String NUM_PARITY_UNITS_KEY = "numParityUnits";
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/AbstractErasureCodec.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/AbstractErasureCodec.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/AbstractErasureCodec.java
index 0cacfbc..e2fb2cb 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/AbstractErasureCodec.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/AbstractErasureCodec.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.codec;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.erasurecode.ECSchema;
import org.apache.hadoop.io.erasurecode.grouper.BlockGrouper;
@@ -24,6 +25,7 @@ import org.apache.hadoop.io.erasurecode.grouper.BlockGrouper;
/**
* Abstract Erasure Codec that implements {@link ErasureCodec}.
*/
+@InterfaceAudience.Private
public abstract class AbstractErasureCodec extends Configured
implements ErasureCodec {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/ErasureCodec.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/ErasureCodec.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/ErasureCodec.java
index 9aa3db2..a2ea865 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/ErasureCodec.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/ErasureCodec.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.codec;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.io.erasurecode.coder.ErasureCoder;
import org.apache.hadoop.io.erasurecode.grouper.BlockGrouper;
@@ -26,6 +27,7 @@ import org.apache.hadoop.io.erasurecode.grouper.BlockGrouper;
* Currently it cares only block grouper and erasure coder. In future we may
* add more aspects here to make the behaviors customizable.
*/
+@InterfaceAudience.Private
public interface ErasureCodec extends Configurable {
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/RSErasureCodec.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/RSErasureCodec.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/RSErasureCodec.java
index 6edd638..7a5786e 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/RSErasureCodec.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/RSErasureCodec.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.codec;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECSchema;
import org.apache.hadoop.io.erasurecode.coder.ErasureCoder;
import org.apache.hadoop.io.erasurecode.coder.RSErasureDecoder;
@@ -25,6 +26,7 @@ import org.apache.hadoop.io.erasurecode.coder.RSErasureEncoder;
/**
* A Reed-Solomon erasure codec.
*/
+@InterfaceAudience.Private
public class RSErasureCodec extends AbstractErasureCodec {
public RSErasureCodec(ECSchema schema) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/XORErasureCodec.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/XORErasureCodec.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/XORErasureCodec.java
index e2dcfa7..9c38fc2 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/XORErasureCodec.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/codec/XORErasureCodec.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.codec;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECSchema;
import org.apache.hadoop.io.erasurecode.coder.ErasureCoder;
import org.apache.hadoop.io.erasurecode.coder.XORErasureDecoder;
@@ -25,6 +26,7 @@ import org.apache.hadoop.io.erasurecode.coder.XORErasureEncoder;
/**
* A XOR erasure codec.
*/
+@InterfaceAudience.Private
public class XORErasureCodec extends AbstractErasureCodec {
public XORErasureCodec(ECSchema schema) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCoder.java
index 5cd0ee8..1d1641f 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.erasurecode.ECSchema;
@@ -25,6 +26,7 @@ import org.apache.hadoop.io.erasurecode.ECSchema;
*
* It implements the {@link ErasureCoder} interface.
*/
+@InterfaceAudience.Private
public abstract class AbstractErasureCoder
extends Configured implements ErasureCoder {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCodingStep.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCodingStep.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCodingStep.java
index c429d49..ccff92d 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCodingStep.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureCodingStep.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECBlock;
/**
@@ -25,6 +26,7 @@ import org.apache.hadoop.io.erasurecode.ECBlock;
*
* It implements {@link ErasureEncodingStep}.
*/
+@InterfaceAudience.Private
public abstract class AbstractErasureCodingStep implements ErasureCodingStep {
private ECBlock[] inputBlocks;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureDecoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureDecoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureDecoder.java
index 3ea9311..6fdae93 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureDecoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureDecoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECBlockGroup;
import org.apache.hadoop.io.erasurecode.ECSchema;
@@ -26,6 +27,7 @@ import org.apache.hadoop.io.erasurecode.ECSchema;
*
* It implements the {@link ErasureCoder} interface.
*/
+@InterfaceAudience.Private
public abstract class AbstractErasureDecoder extends AbstractErasureCoder {
public AbstractErasureDecoder(int numDataUnits, int numParityUnits) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureEncoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureEncoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureEncoder.java
index 7c887e8..5ec6b4e 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureEncoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/AbstractErasureEncoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECBlockGroup;
import org.apache.hadoop.io.erasurecode.ECSchema;
@@ -26,6 +27,7 @@ import org.apache.hadoop.io.erasurecode.ECSchema;
*
* It implements the {@link ErasureCoder} interface.
*/
+@InterfaceAudience.Private
public abstract class AbstractErasureEncoder extends AbstractErasureCoder {
public AbstractErasureEncoder(int numDataUnits, int numParityUnits) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCoder.java
index f05ea41..49cc8dd 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.io.erasurecode.ECBlockGroup;
@@ -34,6 +35,7 @@ import org.apache.hadoop.io.erasurecode.ECBlockGroup;
* of multiple coding steps.
*
*/
+@InterfaceAudience.Private
public interface ErasureCoder extends Configurable {
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCodingStep.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCodingStep.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCodingStep.java
index a3b177f..991eb56 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCodingStep.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureCodingStep.java
@@ -17,12 +17,14 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECChunk;
/**
* Erasure coding step that's involved in encoding/decoding of a block group.
*/
+@InterfaceAudience.Private
public interface ErasureCodingStep {
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureDecodingStep.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureDecodingStep.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureDecodingStep.java
index 980c580..b319cfa 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureDecodingStep.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureDecodingStep.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECChunk;
import org.apache.hadoop.io.erasurecode.rawcoder.RawErasureDecoder;
@@ -25,6 +26,7 @@ import org.apache.hadoop.io.erasurecode.rawcoder.RawErasureDecoder;
* Erasure decoding step, a wrapper of all the necessary information to perform
* a decoding step involved in the whole process of decoding a block group.
*/
+@InterfaceAudience.Private
public class ErasureDecodingStep extends AbstractErasureCodingStep {
private int[] erasedIndexes;
private RawErasureDecoder rawDecoder;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureEncodingStep.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureEncodingStep.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureEncodingStep.java
index bd7587f..311de21 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureEncodingStep.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureEncodingStep.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECChunk;
import org.apache.hadoop.io.erasurecode.rawcoder.RawErasureEncoder;
@@ -25,6 +26,7 @@ import org.apache.hadoop.io.erasurecode.rawcoder.RawErasureEncoder;
* Erasure encoding step, a wrapper of all the necessary information to perform
* an encoding step involved in the whole process of encoding a block group.
*/
+@InterfaceAudience.Private
public class ErasureEncodingStep extends AbstractErasureCodingStep {
private RawErasureEncoder rawEncoder;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureDecoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureDecoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureDecoder.java
index f56674d..6728945 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureDecoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureDecoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.CodecUtil;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECBlockGroup;
@@ -28,6 +29,7 @@ import org.apache.hadoop.io.erasurecode.rawcoder.RawErasureDecoder;
*
* It implements {@link ErasureCoder}.
*/
+@InterfaceAudience.Private
public class RSErasureDecoder extends AbstractErasureDecoder {
private RawErasureDecoder rsRawDecoder;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureEncoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureEncoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureEncoder.java
index 3ed3e20..7784573 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureEncoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/RSErasureEncoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.CodecUtil;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECBlockGroup;
@@ -28,6 +29,7 @@ import org.apache.hadoop.io.erasurecode.rawcoder.RawErasureEncoder;
*
* It implements {@link ErasureCoder}.
*/
+@InterfaceAudience.Private
public class RSErasureEncoder extends AbstractErasureEncoder {
private RawErasureEncoder rawEncoder;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureDecoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureDecoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureDecoder.java
index a847418..a61bafd 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureDecoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureDecoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.CodecUtil;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECBlockGroup;
@@ -28,6 +29,7 @@ import org.apache.hadoop.io.erasurecode.rawcoder.RawErasureDecoder;
*
* It implements {@link ErasureCoder}.
*/
+@InterfaceAudience.Private
public class XORErasureDecoder extends AbstractErasureDecoder {
public XORErasureDecoder(int numDataUnits, int numParityUnits) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureEncoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureEncoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureEncoder.java
index 5c4bcdd..3f22247 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureEncoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureEncoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.coder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.CodecUtil;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECBlockGroup;
@@ -28,6 +29,7 @@ import org.apache.hadoop.io.erasurecode.rawcoder.RawErasureEncoder;
*
* It implements {@link ErasureCoder}.
*/
+@InterfaceAudience.Private
public class XORErasureEncoder extends AbstractErasureEncoder {
public XORErasureEncoder(int numDataUnits, int numParityUnits) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/grouper/BlockGrouper.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/grouper/BlockGrouper.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/grouper/BlockGrouper.java
index bdc1624..3f1b0c2 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/grouper/BlockGrouper.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/grouper/BlockGrouper.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.grouper;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECBlock;
import org.apache.hadoop.io.erasurecode.ECBlockGroup;
import org.apache.hadoop.io.erasurecode.ECSchema;
@@ -25,6 +26,7 @@ import org.apache.hadoop.io.erasurecode.ECSchema;
* As part of a codec, to handle how to form a block group for encoding
* and provide instructions on how to recover erased blocks from a block group
*/
+@InterfaceAudience.Private
public class BlockGrouper {
private ECSchema schema;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureCoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureCoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureCoder.java
index 4b7461e..0ace085 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureCoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureCoder.java
@@ -18,16 +18,17 @@
package org.apache.hadoop.io.erasurecode.rawcoder;
import org.apache.hadoop.HadoopIllegalArgumentException;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configured;
import java.nio.ByteBuffer;
-import java.util.Arrays;
/**
* A common class of basic facilities to be shared by encoder and decoder
*
* It implements the {@link RawErasureCoder} interface.
*/
+@InterfaceAudience.Private
public abstract class AbstractRawErasureCoder
extends Configured implements RawErasureCoder {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureDecoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureDecoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureDecoder.java
index 931cda1..a99730d 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureDecoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureDecoder.java
@@ -18,6 +18,7 @@
package org.apache.hadoop.io.erasurecode.rawcoder;
import org.apache.hadoop.HadoopIllegalArgumentException;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECChunk;
import java.nio.ByteBuffer;
@@ -28,6 +29,7 @@ import java.util.Arrays;
*
* It implements the {@link RawErasureDecoder} interface.
*/
+@InterfaceAudience.Private
public abstract class AbstractRawErasureDecoder extends AbstractRawErasureCoder
implements RawErasureDecoder {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureEncoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureEncoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureEncoder.java
index a0b3cfe..99c754e 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureEncoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/AbstractRawErasureEncoder.java
@@ -18,6 +18,7 @@
package org.apache.hadoop.io.erasurecode.rawcoder;
import org.apache.hadoop.HadoopIllegalArgumentException;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECChunk;
import java.nio.ByteBuffer;
@@ -27,6 +28,7 @@ import java.nio.ByteBuffer;
*
* It implements the {@link RawErasureEncoder} interface.
*/
+@InterfaceAudience.Private
public abstract class AbstractRawErasureEncoder extends AbstractRawErasureCoder
implements RawErasureEncoder {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawDecoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawDecoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawDecoder.java
index 57e6957..69ce3e8 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawDecoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawDecoder.java
@@ -18,6 +18,7 @@
package org.apache.hadoop.io.erasurecode.rawcoder;
import org.apache.hadoop.HadoopIllegalArgumentException;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.rawcoder.util.RSUtil;
import java.nio.ByteBuffer;
@@ -31,6 +32,7 @@ import java.nio.ByteBuffer;
* unnecessarily due to the underlying implementation limit in GF. This will be
* addressed in HADOOP-11871.
*/
+@InterfaceAudience.Private
public class RSRawDecoder extends AbstractRawErasureDecoder {
// To describe and calculate the needed Vandermonde matrix
private int[] errSignature;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawEncoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawEncoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawEncoder.java
index efeee90..813a312 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawEncoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawEncoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.rawcoder.util.RSUtil;
import java.nio.ByteBuffer;
@@ -26,6 +27,7 @@ import java.nio.ByteBuffer;
* isn't available in some environment. Please always use native implementations
* when possible.
*/
+@InterfaceAudience.Private
public class RSRawEncoder extends AbstractRawErasureEncoder {
private int[] generatingPolynomial;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawErasureCoderFactory.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawErasureCoderFactory.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawErasureCoderFactory.java
index 5db49e3..b034cbf 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawErasureCoderFactory.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RSRawErasureCoderFactory.java
@@ -17,9 +17,12 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* A raw coder factory for raw Reed-Solomon coder in Java.
*/
+@InterfaceAudience.Private
public class RSRawErasureCoderFactory implements RawErasureCoderFactory {
@Override
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoder.java
index 0ddb460..082c9c3 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configurable;
/**
@@ -33,6 +34,7 @@ import org.apache.hadoop.conf.Configurable;
* low level constructs, since it only takes care of the math calculation with
* a group of byte buffers.
*/
+@InterfaceAudience.Private
public interface RawErasureCoder extends Configurable {
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoderFactory.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoderFactory.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoderFactory.java
index 280daf3..8a12106 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoderFactory.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoderFactory.java
@@ -17,11 +17,14 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* Raw erasure coder factory that can be used to create raw encoder and decoder.
* It helps in configuration since only one factory class is needed to be
* configured.
*/
+@InterfaceAudience.Private
public interface RawErasureCoderFactory {
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureDecoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureDecoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureDecoder.java
index e2d01d9..fa747d8 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureDecoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureDecoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECChunk;
import java.nio.ByteBuffer;
@@ -28,6 +29,7 @@ import java.nio.ByteBuffer;
*
* It extends the {@link RawErasureCoder} interface.
*/
+@InterfaceAudience.Private
public interface RawErasureDecoder extends RawErasureCoder {
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureEncoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureEncoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureEncoder.java
index 7571f09..d451eb9 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureEncoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureEncoder.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECChunk;
import java.nio.ByteBuffer;
@@ -28,6 +29,7 @@ import java.nio.ByteBuffer;
*
* It extends the {@link RawErasureCoder} interface.
*/
+@InterfaceAudience.Private
public interface RawErasureEncoder extends RawErasureCoder {
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawDecoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawDecoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawDecoder.java
index e20e543..f11dd9f 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawDecoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawDecoder.java
@@ -19,6 +19,8 @@ package org.apache.hadoop.io.erasurecode.rawcoder;
import java.nio.ByteBuffer;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* A raw decoder in XOR code scheme in pure Java, adapted from HDFS-RAID.
*
@@ -26,6 +28,7 @@ import java.nio.ByteBuffer;
* used in advanced codes, like HitchHiker and LRC, though itself is rarely
* deployed independently.
*/
+@InterfaceAudience.Private
public class XORRawDecoder extends AbstractRawErasureDecoder {
public XORRawDecoder(int numDataUnits, int numParityUnits) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawEncoder.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawEncoder.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawEncoder.java
index f4d242e..bc1ae90 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawEncoder.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawEncoder.java
@@ -19,6 +19,8 @@ package org.apache.hadoop.io.erasurecode.rawcoder;
import java.nio.ByteBuffer;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* A raw encoder in XOR code scheme in pure Java, adapted from HDFS-RAID.
*
@@ -26,6 +28,7 @@ import java.nio.ByteBuffer;
* used in advanced codes, like HitchHiker and LRC, though itself is rarely
* deployed independently.
*/
+@InterfaceAudience.Private
public class XORRawEncoder extends AbstractRawErasureEncoder {
public XORRawEncoder(int numDataUnits, int numParityUnits) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawErasureCoderFactory.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawErasureCoderFactory.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawErasureCoderFactory.java
index de20c95..3123690 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawErasureCoderFactory.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/XORRawErasureCoderFactory.java
@@ -17,9 +17,12 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* A raw coder factory for raw XOR coder.
*/
+@InterfaceAudience.Private
public class XORRawErasureCoderFactory implements RawErasureCoderFactory {
@Override
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/DumpUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/DumpUtil.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/DumpUtil.java
index c8f133f..785539c 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/DumpUtil.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/DumpUtil.java
@@ -17,12 +17,14 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder.util;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.io.erasurecode.ECChunk;
/**
* A dump utility class for debugging data erasure coding/decoding issues. Don't
* suggest they are used in runtime production codes.
*/
+@InterfaceAudience.Private
public final class DumpUtil {
private static final String HEX_CHARS_STR = "0123456789ABCDEF";
private static final char[] HEX_CHARS = HEX_CHARS_STR.toCharArray();
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/GaloisField.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/GaloisField.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/GaloisField.java
index 03683b0..fdb47be 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/GaloisField.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/GaloisField.java
@@ -21,10 +21,13 @@ import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* Implementation of Galois field arithmetic with 2^p elements. The input must
* be unsigned integers. It's ported from HDFS-RAID, slightly adapted.
*/
+@InterfaceAudience.Private
public class GaloisField {
// Field size 256 is good for byte based system
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/RSUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/RSUtil.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/RSUtil.java
index 8badf02..d6a10a4 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/RSUtil.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/util/RSUtil.java
@@ -17,9 +17,12 @@
*/
package org.apache.hadoop.io.erasurecode.rawcoder.util;
+import org.apache.hadoop.classification.InterfaceAudience;
+
/**
* Some utilities for Reed-Solomon coding.
*/
+@InterfaceAudience.Private
public class RSUtil {
// We always use the byte system (with symbol size 8, field size 256,
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java
index 8265090..5dadd82 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java
@@ -18,6 +18,7 @@
package org.apache.hadoop.hdfs;
import com.google.common.base.Preconditions;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.ChecksumException;
import org.apache.hadoop.fs.ReadOption;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
@@ -61,6 +62,7 @@ import java.util.concurrent.Future;
/**
* DFSStripedInputStream reads from striped block groups
*/
+@InterfaceAudience.Private
public class DFSStripedInputStream extends DFSInputStream {
private static class ReaderRetryPolicy {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/StripedDataStreamer.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/StripedDataStreamer.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/StripedDataStreamer.java
index f74edc8..ebd04d6 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/StripedDataStreamer.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/StripedDataStreamer.java
@@ -21,6 +21,7 @@ package org.apache.hadoop.hdfs;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdfs.DFSStripedOutputStream.Coordinator;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
@@ -41,6 +42,7 @@ import com.google.common.annotations.VisibleForTesting;
* sends an rpc call to the namenode and then populates the result for the
* other streamers.
*/
+@InterfaceAudience.Private
public class StripedDataStreamer extends DataStreamer {
private final Coordinator coordinator;
private final int index;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ErasureCodingPolicy.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ErasureCodingPolicy.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ErasureCodingPolicy.java
index c976538..068156d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ErasureCodingPolicy.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ErasureCodingPolicy.java
@@ -17,11 +17,15 @@
*/
package org.apache.hadoop.hdfs.protocol;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.io.erasurecode.ECSchema;
/**
* A policy about how to write/read/code an erasure coding file.
*/
+@InterfaceAudience.Public
+@InterfaceStability.Evolving
public final class ErasureCodingPolicy {
private final String name;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index bd539ab..ee6d19d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -173,6 +173,9 @@ Trunk (Unreleased)
HDFS-9182. Cleanup the findbugs and other issues after HDFS EC merged to trunk.
(umamahesh)
+ HDFS-8632. Add InterfaceAudience annotation to the erasure coding classes.
+ (Rakesh R via wang)
+
OPTIMIZATIONS
BUG FIXES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockInfoStriped.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockInfoStriped.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockInfoStriped.java
index d1067b3..d65329e 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockInfoStriped.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockInfoStriped.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.hdfs.server.blockmanagement;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.BlockUCState;
import org.apache.hadoop.hdfs.util.StripedBlockUtil;
@@ -35,6 +36,7 @@ import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
* array's size can be larger than (m+k). Thus currently we use an extra byte
* array to record the block index for each triplet.
*/
+@InterfaceAudience.Private
public class BlockInfoStriped extends BlockInfo {
private final ErasureCodingPolicy ecPolicy;
/**
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicies.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicies.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicies.java
index 622b258..6687e07 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicies.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicies.java
@@ -17,11 +17,13 @@
*/
package org.apache.hadoop.hdfs.server.blockmanagement;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.net.NetworkTopology;
import org.apache.hadoop.util.ReflectionUtils;
+@InterfaceAudience.Private
public class BlockPlacementPolicies{
private final BlockPlacementPolicy replicationPolicy;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
index 0637c18..d7140d8 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
@@ -45,6 +45,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdfs.BlockReader;
@@ -86,6 +87,7 @@ import static org.apache.hadoop.hdfs.util.StripedBlockUtil.convertIndex4Decode;
* response. BPOfferService delegates the work to this class for handling EC
* commands.
*/
+@InterfaceAudience.Private
public final class ErasureCodingWorker {
private static final Log LOG = DataNode.LOG;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/66e2cfa1/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/erasurecode/ECCli.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/erasurecode/ECCli.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/erasurecode/ECCli.java
index 4ed9d0a..c7ce714 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/erasurecode/ECCli.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/erasurecode/ECCli.java
@@ -16,6 +16,7 @@
*/
package org.apache.hadoop.hdfs.tools.erasurecode;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FsShell;
import org.apache.hadoop.fs.shell.CommandFactory;
@@ -25,6 +26,7 @@ import org.apache.hadoop.util.ToolRunner;
/**
* CLI for the erasure code encoding operations.
*/
+@InterfaceAudience.Private
public class ECCli extends FsShell {
private final static String usagePrefix =
[35/35] hadoop git commit: HDFS-8967. Create a BlockManagerLock class
to represent the lock used in the BlockManager. Contributed by Haohui Mai.
Posted by ji...@apache.org.
HDFS-8967. Create a BlockManagerLock class to represent the lock used in the BlockManager. Contributed by Haohui Mai.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/b645d67a
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/b645d67a
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/b645d67a
Branch: refs/heads/HDFS-8966
Commit: b645d67a91087c4f71df2c17498bd9923c7a40f0
Parents: 118a35b
Author: Jing Zhao <ji...@apache.org>
Authored: Tue Oct 6 23:35:24 2015 -0700
Committer: Jing Zhao <ji...@apache.org>
Committed: Thu Oct 8 14:15:14 2015 -0700
----------------------------------------------------------------------
.../server/blockmanagement/BlockManager.java | 124 ++++++++++++-------
.../blockmanagement/BlockManagerLock.java | 50 ++++++++
.../CacheReplicationMonitor.java | 9 +-
.../server/blockmanagement/DatanodeManager.java | 10 +-
.../blockmanagement/DecommissionManager.java | 4 +-
.../blockmanagement/HeartbeatManager.java | 8 +-
.../hdfs/server/namenode/CacheManager.java | 4 +-
.../hdfs/server/namenode/FSNamesystem.java | 5 +
.../hadoop/hdfs/server/namenode/Namesystem.java | 4 +
.../blockmanagement/BlockManagerTestUtil.java | 15 ++-
.../blockmanagement/TestBlockManager.java | 25 ++--
.../blockmanagement/TestDatanodeManager.java | 2 +
.../blockmanagement/TestReplicationPolicy.java | 22 +++-
.../datanode/TestDataNodeVolumeFailure.java | 3 +-
14 files changed, 199 insertions(+), 86 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
index 18bfc41..35e3c1a 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
@@ -94,6 +94,7 @@ import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
import static org.apache.hadoop.hdfs.util.StripedBlockUtil.getInternalBlockLength;
+import org.apache.hadoop.hdfs.util.RwLock;
import org.apache.hadoop.metrics2.util.MBeans;
import org.apache.hadoop.net.Node;
import org.apache.hadoop.security.UserGroupInformation;
@@ -112,7 +113,7 @@ import org.slf4j.LoggerFactory;
* Keeps information related to the blocks stored in the Hadoop cluster.
*/
@InterfaceAudience.Private
-public class BlockManager implements BlockStatsMXBean {
+public class BlockManager implements RwLock, BlockStatsMXBean {
public static final Logger LOG = LoggerFactory.getLogger(BlockManager.class);
public static final Logger blockLog = NameNode.blockStateChangeLog;
@@ -125,6 +126,7 @@ public class BlockManager implements BlockStatsMXBean {
private final Namesystem namesystem;
+ private final BlockManagerLock lock;
private final DatanodeManager datanodeManager;
private final HeartbeatManager heartbeatManager;
private final BlockTokenSecretManager blockTokenSecretManager;
@@ -299,6 +301,7 @@ public class BlockManager implements BlockStatsMXBean {
public BlockManager(final Namesystem namesystem, final Configuration conf)
throws IOException {
this.namesystem = namesystem;
+ this.lock = new BlockManagerLock(namesystem);
datanodeManager = new DatanodeManager(this, namesystem, conf);
heartbeatManager = datanodeManager.getHeartbeatManager();
@@ -518,7 +521,7 @@ public class BlockManager implements BlockStatsMXBean {
/** Dump meta data to out. */
public void metaSave(PrintWriter out) {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
final List<DatanodeDescriptor> live = new ArrayList<DatanodeDescriptor>();
final List<DatanodeDescriptor> dead = new ArrayList<DatanodeDescriptor>();
datanodeManager.fetchDatanodes(live, dead, false);
@@ -550,7 +553,7 @@ public class BlockManager implements BlockStatsMXBean {
// Dump all datanodes
getDatanodeManager().datanodeDump(out);
}
-
+
/**
* Dump the metadata for the given block in a human-readable
* form.
@@ -579,12 +582,12 @@ public class BlockManager implements BlockStatsMXBean {
out.print(fileName + ": ");
}
// l: == live:, d: == decommissioned c: == corrupt e: == excess
- out.print(block + ((usableReplicas > 0)? "" : " MISSING") +
+ out.print(block + ((usableReplicas > 0)? "" : " MISSING") +
" (replicas:" +
" l: " + numReplicas.liveReplicas() +
" d: " + numReplicas.decommissionedAndDecommissioning() +
" c: " + numReplicas.corruptReplicas() +
- " e: " + numReplicas.excessReplicas() + ") ");
+ " e: " + numReplicas.excessReplicas() + ") ");
Collection<DatanodeDescriptor> corruptNodes =
corruptReplicas.getNodes(block);
@@ -929,7 +932,7 @@ public class BlockManager implements BlockStatsMXBean {
final boolean inSnapshot, FileEncryptionInfo feInfo,
ErasureCodingPolicy ecPolicy)
throws IOException {
- assert namesystem.hasReadLock();
+ assert hasReadLock();
if (blocks == null) {
return null;
} else if (blocks.length == 0) {
@@ -963,6 +966,41 @@ public class BlockManager implements BlockStatsMXBean {
}
}
+ @Override
+ public void readLock() {
+ lock.readLock().lock();
+ }
+
+ @Override
+ public void readUnlock() {
+ lock.readLock().unlock();
+ }
+
+ @Override
+ public boolean hasReadLock() {
+ return lock.hasReadLock();
+ }
+
+ @Override
+ public boolean hasWriteLock() {
+ return lock.hasWriteLock();
+ }
+
+ @Override
+ public void writeLock() {
+ lock.writeLock().lock();
+ }
+
+ @Override
+ public void writeLockInterruptibly() throws InterruptedException {
+ lock.writeLock().lockInterruptibly();
+ }
+
+ @Override
+ public void writeUnlock() {
+ lock.writeLock().unlock();
+ }
+
/** @return current access keys. */
public ExportedBlockKeys getBlockKeys() {
return isBlockTokenEnabled()? blockTokenSecretManager.exportKeys()
@@ -1078,12 +1116,12 @@ public class BlockManager implements BlockStatsMXBean {
public BlocksWithLocations getBlocks(DatanodeID datanode, long size
) throws IOException {
namesystem.checkOperation(OperationCategory.READ);
- namesystem.readLock();
+ readLock();
try {
namesystem.checkOperation(OperationCategory.READ);
return getBlocksWithLocations(datanode, size);
} finally {
- namesystem.readUnlock();
+ readUnlock();
}
}
@@ -1146,7 +1184,7 @@ public class BlockManager implements BlockStatsMXBean {
/** Remove the blocks associated to the given DatanodeStorageInfo. */
void removeBlocksAssociatedTo(final DatanodeStorageInfo storageInfo) {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
final Iterator<BlockInfo> it = storageInfo.getBlockIterator();
DatanodeDescriptor node = storageInfo.getDatanodeDescriptor();
while(it.hasNext()) {
@@ -1223,7 +1261,7 @@ public class BlockManager implements BlockStatsMXBean {
*/
public void findAndMarkBlockAsCorrupt(final ExtendedBlock blk,
final DatanodeInfo dn, String storageID, String reason) throws IOException {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
final Block reportedBlock = blk.getLocalBlock();
final BlockInfo storedBlock = getStoredBlock(reportedBlock);
if (storedBlock == null) {
@@ -1401,13 +1439,13 @@ public class BlockManager implements BlockStatsMXBean {
*/
int computeBlockRecoveryWork(int blocksToProcess) {
List<List<BlockInfo>> blocksToReplicate = null;
- namesystem.writeLock();
+ writeLock();
try {
// Choose the blocks to be replicated
blocksToReplicate = neededReplications
.chooseUnderReplicatedBlocks(blocksToProcess);
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
}
return computeRecoveryWorkForBlocks(blocksToReplicate);
}
@@ -1430,7 +1468,7 @@ public class BlockManager implements BlockStatsMXBean {
List<BlockRecoveryWork> recovWork = new LinkedList<>();
// Step 1: categorize at-risk blocks into replication and EC tasks
- namesystem.writeLock();
+ writeLock();
try {
synchronized (neededReplications) {
for (int priority = 0; priority < blocksToRecover.size(); priority++) {
@@ -1443,7 +1481,7 @@ public class BlockManager implements BlockStatsMXBean {
}
}
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
}
// Step 2: choose target nodes for each recovery task
@@ -1465,7 +1503,7 @@ public class BlockManager implements BlockStatsMXBean {
}
// Step 3: add tasks to the DN
- namesystem.writeLock();
+ writeLock();
try {
for(BlockRecoveryWork rw : recovWork){
final DatanodeStorageInfo[] targets = rw.getTargets();
@@ -1481,7 +1519,7 @@ public class BlockManager implements BlockStatsMXBean {
}
}
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
}
if (blockLog.isInfoEnabled()) {
@@ -1851,7 +1889,7 @@ public class BlockManager implements BlockStatsMXBean {
private void processPendingReplications() {
BlockInfo[] timedOutItems = pendingReplications.getTimedOutBlocks();
if (timedOutItems != null) {
- namesystem.writeLock();
+ writeLock();
try {
for (int i = 0; i < timedOutItems.length; i++) {
/*
@@ -1869,7 +1907,7 @@ public class BlockManager implements BlockStatsMXBean {
}
}
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
}
/* If we know the target datanodes where the replication timedout,
* we could invoke decBlocksScheduled() on it. Its ok for now.
@@ -1878,7 +1916,7 @@ public class BlockManager implements BlockStatsMXBean {
}
public long requestBlockReportLeaseId(DatanodeRegistration nodeReg) {
- assert namesystem.hasReadLock();
+ assert hasReadLock();
DatanodeDescriptor node = null;
try {
node = datanodeManager.getDatanode(nodeReg);
@@ -1939,7 +1977,7 @@ public class BlockManager implements BlockStatsMXBean {
final DatanodeStorage storage,
final BlockListAsLongs newReport, BlockReportContext context,
boolean lastStorageInRpc) throws IOException {
- namesystem.writeLock();
+ writeLock();
final long startTime = Time.monotonicNow(); //after acquiring write lock
final long endTime;
DatanodeDescriptor node;
@@ -2015,7 +2053,7 @@ public class BlockManager implements BlockStatsMXBean {
}
} finally {
endTime = Time.monotonicNow();
- namesystem.writeUnlock();
+ writeUnlock();
}
if (invalidatedBlocks != null) {
@@ -2042,7 +2080,7 @@ public class BlockManager implements BlockStatsMXBean {
LOG.warn("processReport 0x{}: removing zombie storage {}, which no " +
"longer exists on the DataNode.",
Long.toHexString(context.getReportId()), zombie.getStorageID());
- assert(namesystem.hasWriteLock());
+ assert hasWriteLock();
Iterator<BlockInfo> iter = zombie.getBlockIterator();
int prevBlocks = zombie.numBlocks();
while (iter.hasNext()) {
@@ -2076,7 +2114,7 @@ public class BlockManager implements BlockStatsMXBean {
long startTimeRescanPostponedMisReplicatedBlocks = Time.monotonicNow();
long startPostponedMisReplicatedBlocksCount =
getPostponedMisreplicatedBlocksCount();
- namesystem.writeLock();
+ writeLock();
try {
// blocksPerRescan is the configured number of blocks per rescan.
// Randomly select blocksPerRescan consecutive blocks from the HashSet
@@ -2129,7 +2167,7 @@ public class BlockManager implements BlockStatsMXBean {
}
}
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
long endPostponedMisReplicatedBlocksCount =
getPostponedMisreplicatedBlocksCount();
LOG.info("Rescan of postponedMisreplicatedBlocks completed in " +
@@ -2191,7 +2229,7 @@ public class BlockManager implements BlockStatsMXBean {
BlockInfo block,
long oldGenerationStamp, long oldNumBytes,
DatanodeStorageInfo[] newStorages) throws IOException {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
BlockToMarkCorrupt b = null;
if (block.getGenerationStamp() != oldGenerationStamp) {
b = new BlockToMarkCorrupt(oldBlock, block, oldGenerationStamp,
@@ -2239,7 +2277,7 @@ public class BlockManager implements BlockStatsMXBean {
final DatanodeStorageInfo storageInfo,
final BlockListAsLongs report) throws IOException {
if (report == null) return;
- assert (namesystem.hasWriteLock());
+ assert (hasWriteLock());
assert (storageInfo.getBlockReportCount() == 0);
for (BlockReportReplica iblk : report) {
@@ -2667,7 +2705,7 @@ public class BlockManager implements BlockStatsMXBean {
private void addStoredBlockImmediate(BlockInfo storedBlock, Block reported,
DatanodeStorageInfo storageInfo)
throws IOException {
- assert (storedBlock != null && namesystem.hasWriteLock());
+ assert (storedBlock != null && hasWriteLock());
if (!namesystem.isInStartupSafeMode()
|| isPopulatingReplQueues()) {
addStoredBlock(storedBlock, reported, storageInfo, null, false);
@@ -2702,7 +2740,7 @@ public class BlockManager implements BlockStatsMXBean {
DatanodeDescriptor delNodeHint,
boolean logEveryBlock)
throws IOException {
- assert block != null && namesystem.hasWriteLock();
+ assert block != null && hasWriteLock();
BlockInfo storedBlock;
DatanodeDescriptor node = storageInfo.getDatanodeDescriptor();
if (!block.isComplete()) {
@@ -2863,7 +2901,7 @@ public class BlockManager implements BlockStatsMXBean {
* over or under replicated. Place it into the respective queue.
*/
public void processMisReplicatedBlocks() {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
stopReplicationInitializer();
neededReplications.clear();
replicationQueuesInitializer = new Daemon() {
@@ -2920,7 +2958,7 @@ public class BlockManager implements BlockStatsMXBean {
while (namesystem.isRunning() && !Thread.currentThread().isInterrupted()) {
int processed = 0;
- namesystem.writeLockInterruptibly();
+ writeLockInterruptibly();
try {
while (processed < numBlocksPerIteration && blocksItr.hasNext()) {
BlockInfo block = blocksItr.next();
@@ -2974,7 +3012,7 @@ public class BlockManager implements BlockStatsMXBean {
break;
}
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
// Make sure it is out of the write lock for sufficiently long time.
Thread.sleep(sleepDuration);
}
@@ -3072,7 +3110,7 @@ public class BlockManager implements BlockStatsMXBean {
private void processOverReplicatedBlock(final BlockInfo block,
final short replication, final DatanodeDescriptor addedNode,
DatanodeDescriptor delNodeHint) {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
if (addedNode == delNodeHint) {
delNodeHint = null;
}
@@ -3110,7 +3148,7 @@ public class BlockManager implements BlockStatsMXBean {
BlockInfo storedBlock, short replication,
DatanodeDescriptor addedNode,
DatanodeDescriptor delNodeHint) {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
// first form a rack to datanodes map and
BlockCollection bc = getBlockCollection(storedBlock);
if (storedBlock.isStriped()) {
@@ -3296,7 +3334,7 @@ public class BlockManager implements BlockStatsMXBean {
}
private void addToExcessReplicate(DatanodeInfo dn, BlockInfo storedBlock) {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
LightWeightLinkedSet<BlockInfo> excessBlocks = excessReplicateMap.get(
dn.getDatanodeUuid());
if (excessBlocks == null) {
@@ -3327,7 +3365,7 @@ public class BlockManager implements BlockStatsMXBean {
*/
public void removeStoredBlock(BlockInfo storedBlock, DatanodeDescriptor node) {
blockLog.debug("BLOCK* removeStoredBlock: {} from {}", storedBlock, node);
- assert (namesystem.hasWriteLock());
+ assert hasWriteLock();
{
if (storedBlock == null || !blocksMap.removeNode(storedBlock, node)) {
blockLog.debug("BLOCK* removeStoredBlock: {} has already been" +
@@ -3504,7 +3542,7 @@ public class BlockManager implements BlockStatsMXBean {
*/
public void processIncrementalBlockReport(final DatanodeID nodeID,
final StorageReceivedDeletedBlocks srdb) throws IOException {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
int received = 0;
int deleted = 0;
int receiving = 0;
@@ -3704,7 +3742,7 @@ public class BlockManager implements BlockStatsMXBean {
}
public void removeBlock(BlockInfo block) {
- assert namesystem.hasWriteLock();
+ assert hasWriteLock();
// No need to ACK blocks that are being removed entirely
// from the namespace, since the removal of the associated
// file already removes them from the block map below.
@@ -3738,7 +3776,7 @@ public class BlockManager implements BlockStatsMXBean {
/** updates a block in under replication queue */
private void updateNeededReplications(final BlockInfo block,
final int curReplicasDelta, int expectedReplicasDelta) {
- namesystem.writeLock();
+ writeLock();
try {
if (!isPopulatingReplQueues()) {
return;
@@ -3756,7 +3794,7 @@ public class BlockManager implements BlockStatsMXBean {
repl.decommissionedAndDecommissioning(), oldExpectedReplicas);
}
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
}
}
@@ -3816,7 +3854,7 @@ public class BlockManager implements BlockStatsMXBean {
private int invalidateWorkForOneNode(DatanodeInfo dn) {
final List<Block> toInvalidate;
- namesystem.writeLock();
+ writeLock();
try {
// blocks should not be replicated or removed if safe mode is on
if (namesystem.isInSafeMode()) {
@@ -3840,7 +3878,7 @@ public class BlockManager implements BlockStatsMXBean {
return 0;
}
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
}
blockLog.debug("BLOCK* {}: ask {} to delete {}", getClass().getSimpleName(),
dn, toInvalidate);
@@ -4093,12 +4131,12 @@ public class BlockManager implements BlockStatsMXBean {
int workFound = this.computeBlockRecoveryWork(blocksToProcess);
// Update counters
- namesystem.writeLock();
+ writeLock();
try {
this.updateState();
this.scheduledReplicationBlocksCount = workFound;
} finally {
- namesystem.writeUnlock();
+ writeUnlock();
}
workFound += this.computeInvalidateWork(nodesToProcess);
return workFound;
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerLock.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerLock.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerLock.java
new file mode 100644
index 0000000..18dc201
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerLock.java
@@ -0,0 +1,50 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.hadoop.hdfs.server.blockmanagement;
+
+import org.apache.hadoop.hdfs.server.namenode.Namesystem;
+
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+class BlockManagerLock implements ReadWriteLock {
+ private final ReentrantReadWriteLock coarseLock;
+
+ BlockManagerLock(Namesystem ns) {
+ this.coarseLock = ns.getLockImplementation();
+ }
+
+ @Override
+ public Lock readLock() {
+ return coarseLock.readLock();
+ }
+
+ @Override
+ public Lock writeLock() {
+ return coarseLock.writeLock();
+ }
+
+ boolean hasReadLock() {
+ return hasWriteLock() || coarseLock.getReadHoldCount() > 0;
+ }
+
+ boolean hasWriteLock() {
+ return coarseLock.isWriteLockedByCurrentThread();
+ }
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java
index 2f81ddf..54bcffd 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java
@@ -55,7 +55,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
-;
/**
* Scans the namesystem, scheduling blocks to be cached as appropriate.
@@ -218,7 +217,7 @@ public class CacheReplicationMonitor extends Thread implements Closeable {
* after are not atomic.
*/
public void waitForRescanIfNeeded() {
- Preconditions.checkArgument(!namesystem.hasWriteLock(),
+ Preconditions.checkArgument(!blockManager.hasWriteLock(),
"Must not hold the FSN write lock when waiting for a rescan.");
Preconditions.checkArgument(lock.isHeldByCurrentThread(),
"Must hold the CRM lock when waiting for a rescan.");
@@ -263,7 +262,7 @@ public class CacheReplicationMonitor extends Thread implements Closeable {
*/
@Override
public void close() throws IOException {
- Preconditions.checkArgument(namesystem.hasWriteLock());
+ Preconditions.checkArgument(blockManager.hasWriteLock());
lock.lock();
try {
if (shutdown) return;
@@ -285,7 +284,7 @@ public class CacheReplicationMonitor extends Thread implements Closeable {
scannedDirectives = 0;
scannedBlocks = 0;
try {
- namesystem.writeLock();
+ blockManager.writeLock();
try {
lock.lock();
if (shutdown) {
@@ -302,7 +301,7 @@ public class CacheReplicationMonitor extends Thread implements Closeable {
rescanCachedBlockMap();
blockManager.getDatanodeManager().resetLastCachingDirectiveSentTime();
} finally {
- namesystem.writeUnlock();
+ blockManager.writeUnlock();
}
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java
index 28ab716..97e4a94 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java
@@ -540,7 +540,7 @@ public class DatanodeManager {
* @param nodeInfo datanode descriptor.
*/
private void removeDatanode(DatanodeDescriptor nodeInfo) {
- assert namesystem.hasWriteLock();
+ assert blockManager.hasWriteLock();
heartbeatManager.removeDatanode(nodeInfo);
blockManager.removeBlocksAssociatedTo(nodeInfo);
networktopology.remove(nodeInfo);
@@ -559,7 +559,7 @@ public class DatanodeManager {
*/
public void removeDatanode(final DatanodeID node
) throws UnregisteredNodeException {
- namesystem.writeLock();
+ blockManager.writeLock();
try {
final DatanodeDescriptor descriptor = getDatanode(node);
if (descriptor != null) {
@@ -569,7 +569,7 @@ public class DatanodeManager {
+ node + " does not exist");
}
} finally {
- namesystem.writeUnlock();
+ blockManager.writeUnlock();
}
}
@@ -993,12 +993,12 @@ public class DatanodeManager {
*/
public void refreshNodes(final Configuration conf) throws IOException {
refreshHostsReader(conf);
- namesystem.writeLock();
+ blockManager.writeLock();
try {
refreshDatanodes();
countSoftwareVersions();
} finally {
- namesystem.writeUnlock();
+ blockManager.writeUnlock();
}
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DecommissionManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DecommissionManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DecommissionManager.java
index fb86ff3..1172ef3 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DecommissionManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DecommissionManager.java
@@ -366,12 +366,12 @@ public class DecommissionManager {
numBlocksChecked = 0;
numNodesChecked = 0;
// Check decom progress
- namesystem.writeLock();
+ blockManager.writeLock();
try {
processPendingNodes();
check();
} finally {
- namesystem.writeUnlock();
+ blockManager.writeUnlock();
}
if (numBlocksChecked + numNodesChecked > 0) {
LOG.info("Checked {} blocks and {} nodes this tick", numBlocksChecked,
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/HeartbeatManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/HeartbeatManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/HeartbeatManager.java
index f2e9827..95adbe4 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/HeartbeatManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/HeartbeatManager.java
@@ -356,7 +356,7 @@ class HeartbeatManager implements DatanodeStatistics {
allAlive = dead == null && failedStorage == null;
if (dead != null) {
// acquire the fsnamesystem lock, and then remove the dead node.
- namesystem.writeLock();
+ blockManager.writeLock();
try {
if (namesystem.isInStartupSafeMode()) {
return;
@@ -365,12 +365,12 @@ class HeartbeatManager implements DatanodeStatistics {
dm.removeDeadDatanode(dead);
}
} finally {
- namesystem.writeUnlock();
+ blockManager.writeUnlock();
}
}
if (failedStorage != null) {
// acquire the fsnamesystem lock, and remove blocks on the storage.
- namesystem.writeLock();
+ blockManager.writeLock();
try {
if (namesystem.isInStartupSafeMode()) {
return;
@@ -379,7 +379,7 @@ class HeartbeatManager implements DatanodeStatistics {
blockManager.removeBlocksAssociatedTo(failedStorage);
}
} finally {
- namesystem.writeUnlock();
+ blockManager.writeUnlock();
}
}
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/CacheManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/CacheManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/CacheManager.java
index 3559065..11797d2 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/CacheManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/CacheManager.java
@@ -928,7 +928,7 @@ public final class CacheManager {
public final void processCacheReport(final DatanodeID datanodeID,
final List<Long> blockIds) throws IOException {
- namesystem.writeLock();
+ blockManager.writeLock();
final long startTime = Time.monotonicNow();
final long endTime;
try {
@@ -942,7 +942,7 @@ public final class CacheManager {
processCacheReportImpl(datanode, blockIds);
} finally {
endTime = Time.monotonicNow();
- namesystem.writeUnlock();
+ blockManager.writeUnlock();
}
// Log the block report processing stats from Namenode perspective
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
index a5b6c77..1ee15a6 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
@@ -6216,6 +6216,11 @@ public class FSNamesystem implements Namesystem, FSNamesystemMBean,
return haContext;
}
+ @Override
+ public ReentrantReadWriteLock getLockImplementation() {
+ return fsLock.coarseLock;
+ }
+
@Override // NameNodeMXBean
public String getCorruptFiles() {
List<String> list = new ArrayList<String>();
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/Namesystem.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/Namesystem.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/Namesystem.java
index b1012c2..89fe678 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/Namesystem.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/Namesystem.java
@@ -30,6 +30,8 @@ import org.apache.hadoop.hdfs.util.RwLock;
import org.apache.hadoop.ipc.StandbyException;
import org.apache.hadoop.security.AccessControlException;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
/** Namesystem operations. */
@InterfaceAudience.Private
public interface Namesystem extends RwLock, SafeMode {
@@ -67,4 +69,6 @@ public interface Namesystem extends RwLock, SafeMode {
CacheManager getCacheManager();
HAContext getHAContext();
+
+ ReentrantReadWriteLock getLockImplementation();
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerTestUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerTestUtil.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerTestUtil.java
index 64d80bd..1ae6c2c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerTestUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerTestUtil.java
@@ -172,10 +172,10 @@ public class BlockManagerTestUtil {
* @param dnName the name of the DataNode
*/
public static void noticeDeadDatanode(NameNode nn, String dnName) {
- FSNamesystem namesystem = nn.getNamesystem();
- namesystem.writeLock();
+ final BlockManager bm = nn.getNamesystem().getBlockManager();
+ bm.writeLock();
try {
- DatanodeManager dnm = namesystem.getBlockManager().getDatanodeManager();
+ DatanodeManager dnm = bm.getDatanodeManager();
HeartbeatManager hbm = dnm.getHeartbeatManager();
DatanodeDescriptor[] dnds = hbm.getDatanodes();
DatanodeDescriptor theDND = null;
@@ -191,7 +191,7 @@ public class BlockManagerTestUtil {
hbm.heartbeatCheck();
}
} finally {
- namesystem.writeUnlock();
+ bm.writeUnlock();
}
}
@@ -220,18 +220,17 @@ public class BlockManagerTestUtil {
* Call heartbeat check function of HeartbeatManager and get
* under replicated blocks count within write lock to make sure
* computeDatanodeWork doesn't interfere.
- * @param namesystem the FSNamesystem
* @param bm the BlockManager to manipulate
* @return the number of under replicated blocks
*/
public static int checkHeartbeatAndGetUnderReplicatedBlocksCount(
- FSNamesystem namesystem, BlockManager bm) {
- namesystem.writeLock();
+ BlockManager bm) {
+ bm.writeLock();
try {
bm.getDatanodeManager().getHeartbeatManager().heartbeatCheck();
return bm.getUnderReplicatedNotMissingBlocks();
} finally {
- namesystem.writeUnlock();
+ bm.writeUnlock();
}
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java
index 094794b..c05c61d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java
@@ -23,6 +23,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.*;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
@@ -34,6 +35,7 @@ import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
+import java.util.concurrent.locks.Lock;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
@@ -63,12 +65,12 @@ import org.junit.Assert;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.Mockito;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Lists;
+import org.mockito.internal.util.reflection.Whitebox;
public class TestBlockManager {
private DatanodeStorageInfo[] storages;
@@ -97,10 +99,15 @@ public class TestBlockManager {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY,
"need to set a dummy value here so it assumes a multi-rack cluster");
- fsn = Mockito.mock(FSNamesystem.class);
- Mockito.doReturn(true).when(fsn).hasWriteLock();
- Mockito.doReturn(true).when(fsn).hasReadLock();
+ fsn = mock(FSNamesystem.class);
+ Lock lockImpl = mock(Lock.class);
+ BlockManagerLock lock = mock(BlockManagerLock.class);
bm = new BlockManager(fsn, conf);
+ Whitebox.setInternalState(bm, "lock", lock);
+ doReturn(true).when(lock).hasWriteLock();
+ doReturn(true).when(lock).hasReadLock();
+ doReturn(lockImpl).when(lock).readLock();
+ doReturn(lockImpl).when(lock).writeLock();
final String[] racks = {
"/rackA",
"/rackA",
@@ -438,9 +445,9 @@ public class TestBlockManager {
private BlockInfo addBlockOnNodes(long blockId, List<DatanodeDescriptor> nodes) {
long inodeId = ++mockINodeId;
- BlockCollection bc = Mockito.mock(BlockCollection.class);
- Mockito.doReturn(inodeId).when(bc).getId();
- Mockito.doReturn(bc).when(fsn).getBlockCollection(inodeId);
+ BlockCollection bc = mock(BlockCollection.class);
+ doReturn(inodeId).when(bc).getId();
+ doReturn(bc).when(fsn).getBlockCollection(inodeId);
BlockInfo blockInfo = blockOnNodes(blockId, nodes);
blockInfo.setReplication((short) 3);
@@ -749,7 +756,7 @@ public class TestBlockManager {
Block block = new Block(blkId);
BlockInfo blockInfo =
new BlockInfoContiguous(block, (short) 3);
- BlockCollection bc = Mockito.mock(BlockCollection.class);
+ BlockCollection bc = mock(BlockCollection.class);
long inodeId = ++mockINodeId;
doReturn(inodeId).when(bc).getId();
bm.blocksMap.addBlockCollection(blockInfo, bc);
@@ -761,7 +768,7 @@ public class TestBlockManager {
Block block = new Block(blkId);
BlockInfo blockInfo = new BlockInfoContiguous(block, (short) 3);
blockInfo.convertToBlockUnderConstruction(UNDER_CONSTRUCTION, null);
- BlockCollection bc = Mockito.mock(BlockCollection.class);
+ BlockCollection bc = mock(BlockCollection.class);
long inodeId = ++mockINodeId;
doReturn(inodeId).when(bc).getId();
bm.blocksMap.addBlockCollection(blockInfo, bc);
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestDatanodeManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestDatanodeManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestDatanodeManager.java
index b55a716..8bad600 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestDatanodeManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestDatanodeManager.java
@@ -55,6 +55,7 @@ import org.apache.hadoop.net.DNSToSwitchMapping;
import org.apache.hadoop.util.Shell;
import org.junit.Assert;
import org.junit.Test;
+import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;
import static org.hamcrest.core.Is.is;
@@ -70,6 +71,7 @@ public class TestDatanodeManager {
private static DatanodeManager mockDatanodeManager(
FSNamesystem fsn, Configuration conf) throws IOException {
BlockManager bm = Mockito.mock(BlockManager.class);
+ Mockito.doReturn(true).when(bm).hasWriteLock();
BlockReportLeaseManager blm = new BlockReportLeaseManager(conf);
Mockito.when(bm.getBlockReportLeaseManager()).thenReturn(blm);
DatanodeManager dm = new DatanodeManager(bm, fsn, conf);
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReplicationPolicy.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReplicationPolicy.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReplicationPolicy.java
index b8a7e77..ba8e966 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReplicationPolicy.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReplicationPolicy.java
@@ -35,6 +35,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.locks.Lock;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.ContentSummary;
@@ -64,6 +65,7 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
+import org.mockito.internal.util.reflection.Whitebox;
@RunWith(Parameterized.class)
public class TestReplicationPolicy extends BaseReplicationPolicyTest {
@@ -1137,9 +1139,11 @@ public class TestReplicationPolicy extends BaseReplicationPolicyTest {
public void testAddStoredBlockDoesNotCauseSkippedReplication()
throws IOException {
Namesystem mockNS = mock(Namesystem.class);
- when(mockNS.hasWriteLock()).thenReturn(true);
- when(mockNS.hasReadLock()).thenReturn(true);
BlockManager bm = new BlockManager(mockNS, new HdfsConfiguration());
+ BlockManagerLock lock = mock(BlockManagerLock.class);
+ when(lock.hasWriteLock()).thenReturn(true);
+ when(lock.hasReadLock()).thenReturn(true);
+ Whitebox.setInternalState(bm, "lock", lock);
UnderReplicatedBlocks underReplicatedBlocks = bm.neededReplications;
BlockInfo block1 = genBlockInfo(ThreadLocalRandom.current().nextLong());
@@ -1186,9 +1190,12 @@ public class TestReplicationPolicy extends BaseReplicationPolicyTest {
testConvertLastBlockToUnderConstructionDoesNotCauseSkippedReplication()
throws IOException {
Namesystem mockNS = mock(Namesystem.class);
- when(mockNS.hasReadLock()).thenReturn(true);
-
BlockManager bm = new BlockManager(mockNS, new HdfsConfiguration());
+ BlockManagerLock lock = mock(BlockManagerLock.class);
+ Lock impl = mock(Lock.class);
+ when(lock.hasReadLock()).thenReturn(true);
+ when(lock.writeLock()).thenReturn(impl);
+ Whitebox.setInternalState(bm, "lock", lock);
UnderReplicatedBlocks underReplicatedBlocks = bm.neededReplications;
long blkID1 = ThreadLocalRandom.current().nextLong();
@@ -1258,9 +1265,12 @@ public class TestReplicationPolicy extends BaseReplicationPolicyTest {
public void testupdateNeededReplicationsDoesNotCauseSkippedReplication()
throws IOException {
Namesystem mockNS = mock(Namesystem.class);
- when(mockNS.hasReadLock()).thenReturn(true);
-
BlockManager bm = new BlockManager(mockNS, new HdfsConfiguration());
+ BlockManagerLock lock = mock(BlockManagerLock.class);
+ Lock impl = mock(Lock.class);
+ when(lock.hasReadLock()).thenReturn(true);
+ when(lock.writeLock()).thenReturn(impl);
+ Whitebox.setInternalState(bm, "lock", lock);
UnderReplicatedBlocks underReplicatedBlocks = bm.neededReplications;
BlockInfo block1 = genBlockInfo(ThreadLocalRandom.current().nextLong());
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b645d67a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeVolumeFailure.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeVolumeFailure.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeVolumeFailure.java
index 2c4fcc5..98519c3 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeVolumeFailure.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeVolumeFailure.java
@@ -393,8 +393,7 @@ public class TestDataNodeVolumeFailure {
// underReplicatedBlocks are due to failed volumes
int underReplicatedBlocks =
- BlockManagerTestUtil.checkHeartbeatAndGetUnderReplicatedBlocksCount(
- cluster.getNamesystem(), bm);
+ BlockManagerTestUtil.checkHeartbeatAndGetUnderReplicatedBlocksCount(bm);
assertTrue("There is no under replicated block after volume failure",
underReplicatedBlocks > 0);
}
[12/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/doc/README
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/doc/README b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/doc/README
deleted file mode 100644
index 1744892..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/doc/README
+++ /dev/null
@@ -1,131 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You 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.
-#
-Fuse-DFS
-
-Supports reads, writes, and directory operations (e.g., cp, ls, more, cat, find, less, rm, mkdir, mv, rmdir). Things like touch, chmod, chown, and permissions are in the works. Fuse-dfs currently shows all files as owned by nobody.
-
-Contributing
-
-It's pretty straightforward to add functionality to fuse-dfs as fuse makes things relatively simple. Some other tasks require also augmenting libhdfs to expose more hdfs functionality to C. See [http://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&mode=hide&pid=12310240&sorter/order=DESC&sorter/field=priority&resolution=-1&component=12312376 contrib/fuse-dfs JIRAs]
-
-Requirements
-
- * Hadoop with compiled libhdfs.so
- * Linux kernel > 2.6.9 with fuse, which is the default or Fuse 2.7.x, 2.8.x installed. See: [http://fuse.sourceforge.net/]
- * modprobe fuse to load it
- * fuse-dfs executable (see below)
- * fuse_dfs_wrapper.sh installed in /bin or other appropriate location (see below)
-
-
-BUILDING
-
- 1. in HADOOP_PREFIX: `ant compile-libhdfs -Dlibhdfs=1
- 2. in HADOOP_PREFIX: `ant package` to deploy libhdfs
- 3. in HADOOP_PREFIX: `ant compile-contrib -Dlibhdfs=1 -Dfusedfs=1`
-
-NOTE: for amd64 architecture, libhdfs will not compile unless you edit
-the Makefile in src/c++/libhdfs/Makefile and set OS_ARCH=amd64
-(probably the same for others too). See [https://issues.apache.org/jira/browse/HADOOP-3344 HADOOP-3344]
-
-Common build problems include not finding the libjvm.so in JAVA_HOME/jre/lib/OS_ARCH/server or not finding fuse in FUSE_HOME or /usr/local.
-
-
-CONFIGURING
-
-Look at all the paths in fuse_dfs_wrapper.sh and either correct them or set them in your environment before running. (note for automount and mount as root, you probably cannot control the environment, so best to set them in the wrapper)
-
-INSTALLING
-
-1. `mkdir /export/hdfs` (or wherever you want to mount it)
-
-2. `fuse_dfs_wrapper.sh dfs://hadoop_server1.foo.com:9000 /export/hdfs -d` and from another terminal, try `ls /export/hdfs`
-
-If 2 works, try again dropping the debug mode, i.e., -d
-
-(note - common problems are that you don't have libhdfs.so or libjvm.so or libfuse.so on your LD_LIBRARY_PATH, and your CLASSPATH does not contain hadoop and other required jars.)
-
-Also note, fuse-dfs will write error/warn messages to the syslog - typically in /var/log/messages
-
-You can use fuse-dfs to mount multiple hdfs instances by just changing the server/port name and directory mount point above.
-
-DEPLOYING
-
-in a root shell do the following:
-
-1. add the following to /etc/fstab
-
-fuse_dfs#dfs://hadoop_server.foo.com:9000 /export/hdfs fuse -oallow_other,rw,-ousetrash,-oinitchecks 0 0
-
-
-2. Mount using: `mount /export/hdfs`. Expect problems with not finding fuse_dfs. You will need to probably add this to /sbin and then problems finding the above 3 libraries. Add these using ldconfig.
-
-
-Fuse DFS takes the following mount options (i.e., on the command line or the comma separated list of options in /etc/fstab:
-
--oserver=%s (optional place to specify the server but in fstab use the format above)
--oport=%d (optional port see comment on server option)
--oentry_timeout=%d (how long directory entries are cached by fuse in seconds - see fuse docs)
--oattribute_timeout=%d (how long attributes are cached by fuse in seconds - see fuse docs)
--oprotected=%s (a colon separated list of directories that fuse-dfs should not allow to be deleted or moved - e.g., /user:/tmp)
--oprivate (not often used but means only the person who does the mount can use the filesystem - aka ! allow_others in fuse speak)
--ordbuffer=%d (in KBs how large a buffer should fuse-dfs use when doing hdfs reads)
-ro
-rw
--ousetrash (should fuse dfs throw things in /Trash when deleting them)
--onotrash (opposite of usetrash)
--odebug (do not daemonize - aka -d in fuse speak)
--obig_writes (use fuse big_writes option so as to allow better performance of writes on kernels >= 2.6.26)
--initchecks - have fuse-dfs try to connect to hdfs to ensure all is ok upon startup. recommended to have this on
-The defaults are:
-
-entry,attribute_timeouts = 60 seconds
-rdbuffer = 10 MB
-protected = null
-debug = 0
-notrash
-private = 0
-
-EXPORTING
-
-Add the following to /etc/exports:
-
-/export/hdfs *.foo.com(no_root_squash,rw,fsid=1,sync)
-
-NOTE - you cannot export this with a FUSE module built into the kernel
-- e.g., kernel 2.6.17. For info on this, refer to the FUSE wiki.
-
-
-RECOMMENDATIONS
-
-1. From /bin, `ln -s $HADOOP_PREFIX/contrib/fuse-dfs/fuse_dfs* .`
-
-2. Always start with debug on so you can see if you are missing a classpath or something like that.
-
-3. use -obig_writes
-
-4. use -initchecks
-
-KNOWN ISSUES
-
-1. if you alias `ls` to `ls --color=auto` and try listing a directory with lots (over thousands) of files, expect it to be slow and at 10s of thousands, expect it to be very very slow. This is because `--color=auto` causes ls to stat every file in the directory. Since fuse-dfs does not cache attribute entries when doing a readdir,
-this is very slow. see [https://issues.apache.org/jira/browse/HADOOP-3797 HADOOP-3797]
-
-2. Writes are approximately 33% slower than the DFSClient. TBD how to optimize this. see: [https://issues.apache.org/jira/browse/HADOOP-3805 HADOOP-3805] - try using -obig_writes if on a >2.6.26 kernel, should perform much better since bigger writes implies less context switching.
-
-3. Reads are ~20-30% slower even with the read buffering.
-
-4. fuse-dfs and underlying libhdfs have no support for permissions. See [https://issues.apache.org/jira/browse/HADOOP-3536 HADOOP-3536]
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_connect.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_connect.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_connect.c
deleted file mode 100644
index 8a2a00b..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_connect.c
+++ /dev/null
@@ -1,644 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_connect.h"
-#include "fuse_dfs.h"
-#include "fuse_users.h"
-#include "libhdfs/hdfs.h"
-#include "util/tree.h"
-
-#include <inttypes.h>
-#include <limits.h>
-#include <poll.h>
-#include <search.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <utime.h>
-
-#define FUSE_CONN_DEFAULT_TIMER_PERIOD 5
-#define FUSE_CONN_DEFAULT_EXPIRY_PERIOD (5 * 60)
-#define HADOOP_SECURITY_AUTHENTICATION "hadoop.security.authentication"
-#define HADOOP_FUSE_CONNECTION_TIMEOUT "hadoop.fuse.connection.timeout"
-#define HADOOP_FUSE_TIMER_PERIOD "hadoop.fuse.timer.period"
-
-/** Length of the buffer needed by asctime_r */
-#define TIME_STR_LEN 26
-
-struct hdfsConn;
-
-static int hdfsConnCompare(const struct hdfsConn *a, const struct hdfsConn *b);
-static void hdfsConnExpiry(void);
-static void* hdfsConnExpiryThread(void *v);
-
-RB_HEAD(hdfsConnTree, hdfsConn);
-
-enum authConf {
- AUTH_CONF_UNKNOWN,
- AUTH_CONF_KERBEROS,
- AUTH_CONF_OTHER,
-};
-
-struct hdfsConn {
- RB_ENTRY(hdfsConn) entry;
- /** How many threads are currently using this hdfsConnection object */
- int64_t refcnt;
- /** The username used to make this connection. Dynamically allocated. */
- char *usrname;
- /** Kerberos ticket cache path, or NULL if this is not a kerberized
- * connection. Dynamically allocated. */
- char *kpath;
- /** mtime of the kpath, if the kpath is non-NULL */
- time_t kPathMtime;
- /** nanosecond component of the mtime of the kpath, if the kpath is non-NULL */
- long kPathMtimeNs;
- /** The cached libhdfs fs instance */
- hdfsFS fs;
- /** Nonzero if this hdfs connection needs to be closed as soon as possible.
- * If this is true, the connection has been removed from the tree. */
- int condemned;
- /** Number of times we should run the expiration timer on this connection
- * before removing it. */
- int expirationCount;
-};
-
-RB_GENERATE(hdfsConnTree, hdfsConn, entry, hdfsConnCompare);
-
-/** Current cached libhdfs connections */
-static struct hdfsConnTree gConnTree;
-
-/** The URI used to make our connections. Dynamically allocated. */
-static char *gUri;
-
-/** The port used to make our connections, or 0. */
-static int gPort;
-
-/** Lock which protects gConnTree and gConnectTimer->active */
-static pthread_mutex_t gConnMutex;
-
-/** Type of authentication configured */
-static enum authConf gHdfsAuthConf;
-
-/** FUSE connection timer expiration period */
-static int32_t gTimerPeriod;
-
-/** FUSE connection expiry period */
-static int32_t gExpiryPeriod;
-
-/** FUSE timer expiration thread */
-static pthread_t gTimerThread;
-
-/**
- * Find out what type of authentication the system administrator
- * has configured.
- *
- * @return the type of authentication, or AUTH_CONF_UNKNOWN on error.
- */
-static enum authConf discoverAuthConf(void)
-{
- int ret;
- char *val = NULL;
- enum authConf authConf;
-
- ret = hdfsConfGetStr(HADOOP_SECURITY_AUTHENTICATION, &val);
- if (ret)
- authConf = AUTH_CONF_UNKNOWN;
- else if (!val)
- authConf = AUTH_CONF_OTHER;
- else if (!strcmp(val, "kerberos"))
- authConf = AUTH_CONF_KERBEROS;
- else
- authConf = AUTH_CONF_OTHER;
- free(val);
- return authConf;
-}
-
-int fuseConnectInit(const char *nnUri, int port)
-{
- int ret;
-
- gTimerPeriod = FUSE_CONN_DEFAULT_TIMER_PERIOD;
- ret = hdfsConfGetInt(HADOOP_FUSE_TIMER_PERIOD, &gTimerPeriod);
- if (ret) {
- fprintf(stderr, "Unable to determine the configured value for %s.",
- HADOOP_FUSE_TIMER_PERIOD);
- return -EINVAL;
- }
- if (gTimerPeriod < 1) {
- fprintf(stderr, "Invalid value %d given for %s.\n",
- gTimerPeriod, HADOOP_FUSE_TIMER_PERIOD);
- return -EINVAL;
- }
- gExpiryPeriod = FUSE_CONN_DEFAULT_EXPIRY_PERIOD;
- ret = hdfsConfGetInt(HADOOP_FUSE_CONNECTION_TIMEOUT, &gExpiryPeriod);
- if (ret) {
- fprintf(stderr, "Unable to determine the configured value for %s.",
- HADOOP_FUSE_CONNECTION_TIMEOUT);
- return -EINVAL;
- }
- if (gExpiryPeriod < 1) {
- fprintf(stderr, "Invalid value %d given for %s.\n",
- gExpiryPeriod, HADOOP_FUSE_CONNECTION_TIMEOUT);
- return -EINVAL;
- }
- gHdfsAuthConf = discoverAuthConf();
- if (gHdfsAuthConf == AUTH_CONF_UNKNOWN) {
- fprintf(stderr, "Unable to determine the configured value for %s.",
- HADOOP_SECURITY_AUTHENTICATION);
- return -EINVAL;
- }
- gPort = port;
- gUri = strdup(nnUri);
- if (!gUri) {
- fprintf(stderr, "fuseConnectInit: OOM allocting nnUri\n");
- return -ENOMEM;
- }
- ret = pthread_mutex_init(&gConnMutex, NULL);
- if (ret) {
- free(gUri);
- fprintf(stderr, "fuseConnectInit: pthread_mutex_init failed with error %d\n",
- ret);
- return -ret;
- }
- RB_INIT(&gConnTree);
- ret = pthread_create(&gTimerThread, NULL, hdfsConnExpiryThread, NULL);
- if (ret) {
- free(gUri);
- pthread_mutex_destroy(&gConnMutex);
- fprintf(stderr, "fuseConnectInit: pthread_create failed with error %d\n",
- ret);
- return -ret;
- }
- fprintf(stderr, "fuseConnectInit: initialized with timer period %d, "
- "expiry period %d\n", gTimerPeriod, gExpiryPeriod);
- return 0;
-}
-
-/**
- * Compare two libhdfs connections by username
- *
- * @param a The first libhdfs connection
- * @param b The second libhdfs connection
- *
- * @return -1, 0, or 1 depending on a < b, a ==b, a > b
- */
-static int hdfsConnCompare(const struct hdfsConn *a, const struct hdfsConn *b)
-{
- return strcmp(a->usrname, b->usrname);
-}
-
-/**
- * Find a libhdfs connection by username
- *
- * @param usrname The username to look up
- *
- * @return The connection, or NULL if none could be found
- */
-static struct hdfsConn* hdfsConnFind(const char *usrname)
-{
- struct hdfsConn exemplar;
-
- memset(&exemplar, 0, sizeof(exemplar));
- exemplar.usrname = (char*)usrname;
- return RB_FIND(hdfsConnTree, &gConnTree, &exemplar);
-}
-
-/**
- * Free the resource associated with a libhdfs connection.
- *
- * You must remove the connection from the tree before calling this function.
- *
- * @param conn The libhdfs connection
- */
-static void hdfsConnFree(struct hdfsConn *conn)
-{
- int ret;
-
- ret = hdfsDisconnect(conn->fs);
- if (ret) {
- fprintf(stderr, "hdfsConnFree(username=%s): "
- "hdfsDisconnect failed with error %d\n",
- (conn->usrname ? conn->usrname : "(null)"), ret);
- }
- free(conn->usrname);
- free(conn->kpath);
- free(conn);
-}
-
-/**
- * Convert a time_t to a string.
- *
- * @param sec time in seconds since the epoch
- * @param buf (out param) output buffer
- * @param bufLen length of output buffer
- *
- * @return 0 on success; ENAMETOOLONG if the provided buffer was
- * too short
- */
-static int timeToStr(time_t sec, char *buf, size_t bufLen)
-{
- struct tm tm, *out;
- size_t l;
-
- if (bufLen < TIME_STR_LEN) {
- return -ENAMETOOLONG;
- }
- out = localtime_r(&sec, &tm);
- asctime_r(out, buf);
- // strip trailing newline
- l = strlen(buf);
- if (l != 0)
- buf[l - 1] = '\0';
- return 0;
-}
-
-/**
- * Check an HDFS connection's Kerberos path.
- *
- * If the mtime of the Kerberos ticket cache file has changed since we first
- * opened the connection, mark the connection as condemned and remove it from
- * the hdfs connection tree.
- *
- * @param conn The HDFS connection
- */
-static int hdfsConnCheckKpath(const struct hdfsConn *conn)
-{
- int ret;
- struct stat st;
- char prevTimeBuf[TIME_STR_LEN], newTimeBuf[TIME_STR_LEN];
-
- if (stat(conn->kpath, &st) < 0) {
- ret = errno;
- if (ret == ENOENT) {
- fprintf(stderr, "hdfsConnCheckKpath(conn.usrname=%s): the kerberos "
- "ticket cache file '%s' has disappeared. Condemning the "
- "connection.\n", conn->usrname, conn->kpath);
- } else {
- fprintf(stderr, "hdfsConnCheckKpath(conn.usrname=%s): stat(%s) "
- "failed with error code %d. Pessimistically condemning the "
- "connection.\n", conn->usrname, conn->kpath, ret);
- }
- return -ret;
- }
- if ((st.st_mtim.tv_sec != conn->kPathMtime) ||
- (st.st_mtim.tv_nsec != conn->kPathMtimeNs)) {
- timeToStr(conn->kPathMtime, prevTimeBuf, sizeof(prevTimeBuf));
- timeToStr(st.st_mtim.tv_sec, newTimeBuf, sizeof(newTimeBuf));
- fprintf(stderr, "hdfsConnCheckKpath(conn.usrname=%s): mtime on '%s' "
- "has changed from '%s' to '%s'. Condemning the connection "
- "because our cached Kerberos credentials have probably "
- "changed.\n", conn->usrname, conn->kpath, prevTimeBuf, newTimeBuf);
- return -EINTERNAL;
- }
- return 0;
-}
-
-/**
- * Cache expiration logic.
- *
- * This function is called periodically by the cache expiration thread. For
- * each FUSE connection not currently in use (refcnt == 0) it will decrement the
- * expirationCount for that connection. Once the expirationCount reaches 0 for
- * a connection, it can be garbage collected.
- *
- * We also check to see if the Kerberos credentials have changed. If so, the
- * connecton is immediately condemned, even if it is currently in use.
- */
-static void hdfsConnExpiry(void)
-{
- struct hdfsConn *conn, *tmpConn;
-
- pthread_mutex_lock(&gConnMutex);
- RB_FOREACH_SAFE(conn, hdfsConnTree, &gConnTree, tmpConn) {
- if (conn->kpath) {
- if (hdfsConnCheckKpath(conn)) {
- conn->condemned = 1;
- RB_REMOVE(hdfsConnTree, &gConnTree, conn);
- if (conn->refcnt == 0) {
- /* If the connection is not in use by any threads, delete it
- * immediately. If it is still in use by some threads, the last
- * thread using it will clean it up later inside hdfsConnRelease. */
- hdfsConnFree(conn);
- continue;
- }
- }
- }
- if (conn->refcnt == 0) {
- /* If the connection is not currently in use by a thread, check to see if
- * it ought to be removed because it's too old. */
- conn->expirationCount--;
- if (conn->expirationCount <= 0) {
- if (conn->condemned) {
- fprintf(stderr, "hdfsConnExpiry: LOGIC ERROR: condemned connection "
- "as %s is still in the tree!\n", conn->usrname);
- }
- fprintf(stderr, "hdfsConnExpiry: freeing and removing connection as "
- "%s because it's now too old.\n", conn->usrname);
- RB_REMOVE(hdfsConnTree, &gConnTree, conn);
- hdfsConnFree(conn);
- }
- }
- }
- pthread_mutex_unlock(&gConnMutex);
-}
-
-// The Kerberos FILE: prefix. This indicates that the kerberos ticket cache
-// specifier is a file. (Note that we also assume that the specifier is a file
-// if no prefix is present.)
-#define KRB_FILE_PREFIX "FILE:"
-
-// Length of the Kerberos file prefix, which is equal to the string size in
-// bytes minus 1 (because we don't count the null terminator in the length.)
-#define KRB_FILE_PREFIX_LEN (sizeof(KRB_FILE_PREFIX) - 1)
-
-/**
- * Find the Kerberos ticket cache path.
- *
- * This function finds the Kerberos ticket cache path from the thread ID and
- * user ID of the process making the request.
- *
- * Normally, the ticket cache path is in a well-known location in /tmp.
- * However, it's possible that the calling process could set the KRB5CCNAME
- * environment variable, indicating that its Kerberos ticket cache is at a
- * non-default location. We try to handle this possibility by reading the
- * process' environment here. This will be allowed if we have root
- * capabilities, or if our UID is the same as the remote process' UID.
- *
- * Note that we don't check to see if the cache file actually exists or not.
- * We're just trying to find out where it would be if it did exist.
- *
- * @param path (out param) the path to the ticket cache file
- * @param pathLen length of the path buffer
- */
-static void findKerbTicketCachePath(struct fuse_context *ctx,
- char *path, size_t pathLen)
-{
- FILE *fp = NULL;
- static const char * const KRB5CCNAME = "\0KRB5CCNAME=";
- int c = '\0', pathIdx = 0, keyIdx = 0;
- size_t KRB5CCNAME_LEN = strlen(KRB5CCNAME + 1) + 1;
-
- // /proc/<tid>/environ contains the remote process' environment. It is
- // exposed to us as a series of KEY=VALUE pairs, separated by NULL bytes.
- snprintf(path, pathLen, "/proc/%d/environ", ctx->pid);
- fp = fopen(path, "r");
- if (!fp)
- goto done;
- while (1) {
- if (c == EOF)
- goto done;
- if (keyIdx == KRB5CCNAME_LEN) {
- if (pathIdx >= pathLen - 1)
- goto done;
- if (c == '\0')
- goto done;
- path[pathIdx++] = c;
- } else if (KRB5CCNAME[keyIdx++] != c) {
- keyIdx = 0;
- }
- c = fgetc(fp);
- }
-
-done:
- if (fp)
- fclose(fp);
- if (pathIdx == 0) {
- snprintf(path, pathLen, "/tmp/krb5cc_%d", ctx->uid);
- } else {
- path[pathIdx] = '\0';
- }
- if (strncmp(path, KRB_FILE_PREFIX, KRB_FILE_PREFIX_LEN) == 0) {
- fprintf(stderr, "stripping " KRB_FILE_PREFIX " from the front of "
- "KRB5CCNAME.\n");
- memmove(path, path + KRB_FILE_PREFIX_LEN,
- strlen(path + KRB_FILE_PREFIX_LEN) + 1);
- }
-}
-
-/**
- * Create a new libhdfs connection.
- *
- * @param usrname Username to use for the new connection
- * @param ctx FUSE context to use for the new connection
- * @param out (out param) the new libhdfs connection
- *
- * @return 0 on success; error code otherwise
- */
-static int fuseNewConnect(const char *usrname, struct fuse_context *ctx,
- struct hdfsConn **out)
-{
- struct hdfsBuilder *bld = NULL;
- char kpath[PATH_MAX] = { 0 };
- struct hdfsConn *conn = NULL;
- int ret;
- struct stat st;
-
- conn = calloc(1, sizeof(struct hdfsConn));
- if (!conn) {
- fprintf(stderr, "fuseNewConnect: OOM allocating struct hdfsConn\n");
- ret = -ENOMEM;
- goto error;
- }
- bld = hdfsNewBuilder();
- if (!bld) {
- fprintf(stderr, "Unable to create hdfs builder\n");
- ret = -ENOMEM;
- goto error;
- }
- /* We always want to get a new FileSystem instance here-- that's why we call
- * hdfsBuilderSetForceNewInstance. Otherwise the 'cache condemnation' logic
- * in hdfsConnExpiry will not work correctly, since FileSystem might re-use the
- * existing cached connection which we wanted to get rid of.
- */
- hdfsBuilderSetForceNewInstance(bld);
- hdfsBuilderSetNameNode(bld, gUri);
- if (gPort) {
- hdfsBuilderSetNameNodePort(bld, gPort);
- }
- hdfsBuilderSetUserName(bld, usrname);
- if (gHdfsAuthConf == AUTH_CONF_KERBEROS) {
- findKerbTicketCachePath(ctx, kpath, sizeof(kpath));
- if (stat(kpath, &st) < 0) {
- fprintf(stderr, "fuseNewConnect: failed to find Kerberos ticket cache "
- "file '%s'. Did you remember to kinit for UID %d?\n",
- kpath, ctx->uid);
- ret = -EACCES;
- goto error;
- }
- conn->kPathMtime = st.st_mtim.tv_sec;
- conn->kPathMtimeNs = st.st_mtim.tv_nsec;
- hdfsBuilderSetKerbTicketCachePath(bld, kpath);
- conn->kpath = strdup(kpath);
- if (!conn->kpath) {
- fprintf(stderr, "fuseNewConnect: OOM allocating kpath\n");
- ret = -ENOMEM;
- goto error;
- }
- }
- conn->usrname = strdup(usrname);
- if (!conn->usrname) {
- fprintf(stderr, "fuseNewConnect: OOM allocating usrname\n");
- ret = -ENOMEM;
- goto error;
- }
- conn->fs = hdfsBuilderConnect(bld);
- bld = NULL;
- if (!conn->fs) {
- ret = errno;
- fprintf(stderr, "fuseNewConnect(usrname=%s): Unable to create fs: "
- "error code %d\n", usrname, ret);
- goto error;
- }
- RB_INSERT(hdfsConnTree, &gConnTree, conn);
- *out = conn;
- return 0;
-
-error:
- if (bld) {
- hdfsFreeBuilder(bld);
- }
- if (conn) {
- free(conn->kpath);
- free(conn->usrname);
- free(conn);
- }
- return ret;
-}
-
-int fuseConnect(const char *usrname, struct fuse_context *ctx,
- struct hdfsConn **out)
-{
- int ret;
- struct hdfsConn* conn;
-
- pthread_mutex_lock(&gConnMutex);
- conn = hdfsConnFind(usrname);
- if (!conn) {
- ret = fuseNewConnect(usrname, ctx, &conn);
- if (ret) {
- pthread_mutex_unlock(&gConnMutex);
- fprintf(stderr, "fuseConnect(usrname=%s): fuseNewConnect failed with "
- "error code %d\n", usrname, ret);
- return ret;
- }
- }
- conn->refcnt++;
- conn->expirationCount = (gExpiryPeriod + gTimerPeriod - 1) / gTimerPeriod;
- if (conn->expirationCount < 2)
- conn->expirationCount = 2;
- pthread_mutex_unlock(&gConnMutex);
- *out = conn;
- return 0;
-}
-
-int fuseConnectAsThreadUid(struct hdfsConn **conn)
-{
- struct fuse_context *ctx;
- char *usrname;
- int ret;
-
- ctx = fuse_get_context();
- usrname = getUsername(ctx->uid);
- ret = fuseConnect(usrname, ctx, conn);
- free(usrname);
- return ret;
-}
-
-int fuseConnectTest(void)
-{
- int ret;
- struct hdfsConn *conn;
-
- if (gHdfsAuthConf == AUTH_CONF_KERBEROS) {
- // TODO: call some method which can tell us whether the FS exists. In order
- // to implement this, we have to add a method to FileSystem in order to do
- // this without valid Kerberos authentication. See HDFS-3674 for details.
- return 0;
- }
- ret = fuseNewConnect("root", NULL, &conn);
- if (ret) {
- fprintf(stderr, "fuseConnectTest failed with error code %d\n", ret);
- return ret;
- }
- hdfsConnRelease(conn);
- return 0;
-}
-
-struct hdfs_internal* hdfsConnGetFs(struct hdfsConn *conn)
-{
- return conn->fs;
-}
-
-void hdfsConnRelease(struct hdfsConn *conn)
-{
- pthread_mutex_lock(&gConnMutex);
- conn->refcnt--;
- if ((conn->refcnt == 0) && (conn->condemned)) {
- fprintf(stderr, "hdfsConnRelease(usrname=%s): freeing condemend FS!\n",
- conn->usrname);
- /* Notice that we're not removing the connection from gConnTree here.
- * If the connection is condemned, it must have already been removed from
- * the tree, so that no other threads start using it.
- */
- hdfsConnFree(conn);
- }
- pthread_mutex_unlock(&gConnMutex);
-}
-
-/**
- * Get the monotonic time.
- *
- * Unlike the wall-clock time, monotonic time only ever goes forward. If the
- * user adjusts the time, the monotonic time will not be affected.
- *
- * @return The monotonic time
- */
-static time_t getMonotonicTime(void)
-{
- int res;
- struct timespec ts;
-
- res = clock_gettime(CLOCK_MONOTONIC, &ts);
- if (res)
- abort();
- return ts.tv_sec;
-}
-
-/**
- * FUSE connection expiration thread
- *
- */
-static void* hdfsConnExpiryThread(void *v)
-{
- time_t nextTime, curTime;
- int waitTime;
-
- nextTime = getMonotonicTime() + gTimerPeriod;
- while (1) {
- curTime = getMonotonicTime();
- if (curTime >= nextTime) {
- hdfsConnExpiry();
- nextTime = curTime + gTimerPeriod;
- }
- waitTime = (nextTime - curTime) * 1000;
- poll(NULL, 0, waitTime);
- }
- return NULL;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_connect.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_connect.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_connect.h
deleted file mode 100644
index 35645c6..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_connect.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_CONNECT_H__
-#define __FUSE_CONNECT_H__
-
-struct fuse_context;
-struct hdfsConn;
-struct hdfs_internal;
-
-/**
- * Initialize the fuse connection subsystem.
- *
- * This must be called before any of the other functions in this module.
- *
- * @param nnUri The NameNode URI
- * @param port The NameNode port
- *
- * @return 0 on success; error code otherwise
- */
-int fuseConnectInit(const char *nnUri, int port);
-
-/**
- * Get a libhdfs connection.
- *
- * If there is an existing connection, it will be reused. If not, a new one
- * will be created.
- *
- * You must call hdfsConnRelease on the connection you get back!
- *
- * @param usrname The username to use
- * @param ctx The FUSE context to use (contains UID, PID of requestor)
- * @param conn (out param) The HDFS connection
- *
- * @return 0 on success; error code otherwise
- */
-int fuseConnect(const char *usrname, struct fuse_context *ctx,
- struct hdfsConn **out);
-
-/**
- * Get a libhdfs connection.
- *
- * The same as fuseConnect, except the username will be determined from the FUSE
- * thread context.
- *
- * @param conn (out param) The HDFS connection
- *
- * @return 0 on success; error code otherwise
- */
-int fuseConnectAsThreadUid(struct hdfsConn **conn);
-
-/**
- * Test whether we can connect to the HDFS cluster
- *
- * @return 0 on success; error code otherwise
- */
-int fuseConnectTest(void);
-
-/**
- * Get the hdfsFS associated with an hdfsConn.
- *
- * @param conn The hdfsConn
- *
- * @return the hdfsFS
- */
-struct hdfs_internal* hdfsConnGetFs(struct hdfsConn *conn);
-
-/**
- * Release an hdfsConn when we're done with it.
- *
- * @param conn The hdfsConn
- */
-void hdfsConnRelease(struct hdfsConn *conn);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_context_handle.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_context_handle.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_context_handle.h
deleted file mode 100644
index 6929062..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_context_handle.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_CONTEXT_HANDLE_H__
-#define __FUSE_CONTEXT_HANDLE_H__
-
-#include <hdfs.h>
-#include <stddef.h>
-#include <sys/types.h>
-
-//
-// Structure to store fuse_dfs specific data
-// this will be created and passed to fuse at startup
-// and fuse will pass it back to us via the context function
-// on every operation.
-//
-typedef struct dfs_context_struct {
- int debug;
- int usetrash;
- int direct_io;
- char **protectedpaths;
- size_t rdbuffer_size;
-} dfs_context;
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs.c
deleted file mode 100644
index f693032..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs.c
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_options.h"
-#include "fuse_impls.h"
-#include "fuse_init.h"
-#include "fuse_connect.h"
-
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-int is_protected(const char *path) {
-
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
- assert(dfs != NULL);
- assert(dfs->protectedpaths);
-
- int i ;
- for (i = 0; dfs->protectedpaths[i]; i++) {
- if (strcmp(path, dfs->protectedpaths[i]) == 0) {
- return 1;
- }
- }
- return 0;
-}
-
-static struct fuse_operations dfs_oper = {
- .getattr = dfs_getattr,
- .access = dfs_access,
- .readdir = dfs_readdir,
- .destroy = dfs_destroy,
- .init = dfs_init,
- .open = dfs_open,
- .read = dfs_read,
- .symlink = dfs_symlink,
- .statfs = dfs_statfs,
- .mkdir = dfs_mkdir,
- .rmdir = dfs_rmdir,
- .rename = dfs_rename,
- .unlink = dfs_unlink,
- .release = dfs_release,
- .create = dfs_create,
- .write = dfs_write,
- .flush = dfs_flush,
- .mknod = dfs_mknod,
- .utimens = dfs_utimens,
- .chmod = dfs_chmod,
- .chown = dfs_chown,
- .truncate = dfs_truncate,
-};
-
-int main(int argc, char *argv[])
-{
- int ret;
-
- umask(0);
-
- extern const char *program;
- program = argv[0];
- struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
-
- memset(&options, 0, sizeof(struct options));
-
- options.rdbuffer_size = 10*1024*1024;
- options.attribute_timeout = 60;
- options.entry_timeout = 60;
-
- if (-1 == fuse_opt_parse(&args, &options, dfs_opts, dfs_options)) {
- return -1;
- }
-
- if (!options.private) {
- fuse_opt_add_arg(&args, "-oallow_other");
- }
-
- if (!options.no_permissions) {
- fuse_opt_add_arg(&args, "-odefault_permissions");
- }
- /*
- * FUSE already has a built-in parameter for mounting the filesystem as
- * read-only, -r. We defined our own parameter for doing this called -oro.
- * We support it by translating it into -r internally.
- * The kernel intercepts and returns an error message for any "write"
- * operations that the user attempts to perform on a read-only filesystem.
- * That means that we don't have to write any code to handle read-only mode.
- * See HDFS-4139 for more details.
- */
- if (options.read_only) {
- fuse_opt_add_arg(&args, "-r");
- }
-
- {
- char buf[80];
-
- snprintf(buf, sizeof buf, "-oattr_timeout=%d",options.attribute_timeout);
- fuse_opt_add_arg(&args, buf);
-
- snprintf(buf, sizeof buf, "-oentry_timeout=%d",options.entry_timeout);
- fuse_opt_add_arg(&args, buf);
- }
-
- if (options.nn_uri == NULL) {
- print_usage(argv[0]);
- exit(EXIT_SUCCESS);
- }
-
- /* Note: do not call any libhdfs functions until fuse_main has been invoked.
- *
- * fuse_main will daemonize this process, by calling fork(). This will cause
- * any extant threads to be destroyed, which could cause problems if
- * libhdfs has started some Java threads.
- *
- * Most initialization code should go in dfs_init, which is invoked after the
- * fork. See HDFS-3808 for details.
- */
- ret = fuse_main(args.argc, args.argv, &dfs_oper, NULL);
- fuse_opt_free_args(&args);
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs.h
deleted file mode 100644
index 4554dbd..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_DFS_H__
-#define __FUSE_DFS_H__
-
-#define FUSE_USE_VERSION 26
-
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-#include <assert.h>
-#include <strings.h>
-#include <syslog.h>
-
-#include <fuse.h>
-#include <fuse/fuse_opt.h>
-
-#include <sys/xattr.h>
-
-#include "config.h"
-
-//
-// Check if a path is in the mount option supplied protected paths.
-//
-int is_protected(const char *path);
-
-#undef INFO
-#define INFO(_fmt, ...) { \
- fprintf(stdout, "INFO %s:%d " _fmt "\n", \
- __FILE__, __LINE__, ## __VA_ARGS__); \
- syslog(LOG_INFO, "INFO %s:%d " _fmt "\n", \
- __FILE__, __LINE__, ## __VA_ARGS__); \
-}
-
-#undef DEBUG
-#define DEBUG(_fmt, ...) { \
- fprintf(stdout, "DEBUG %s:%d " _fmt "\n", \
- __FILE__, __LINE__, ## __VA_ARGS__); \
- syslog(LOG_DEBUG, "DEBUG %s:%d " _fmt "\n", \
- __FILE__, __LINE__, ## __VA_ARGS__); \
-}
-
-#undef ERROR
-#define ERROR(_fmt, ...) { \
- fprintf(stderr, "ERROR %s:%d " _fmt "\n", \
- __FILE__, __LINE__, ## __VA_ARGS__); \
- syslog(LOG_ERR, "ERROR %s:%d " _fmt "\n", \
- __FILE__, __LINE__, ## __VA_ARGS__); \
-}
-
-//#define DOTRACE
-#ifdef DOTRACE
-#define TRACE(x) { \
- DEBUG("TRACE %s", x); \
-}
-
-#define TRACE1(x,y) { \
- DEBUG("TRACE %s %s\n", x, y); \
-}
-#else
-#define TRACE(x) ;
-#define TRACE1(x,y) ;
-#endif
-
-#endif // __FUSE_DFS_H__
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs_wrapper.sh
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs_wrapper.sh b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs_wrapper.sh
deleted file mode 100755
index 97239cc..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_dfs_wrapper.sh
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/env bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You 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.
-#
-
-export HADOOP_PREFIX=${HADOOP_PREFIX:-/usr/local/share/hadoop}
-
-if [ "$OS_ARCH" = "" ]; then
-export OS_ARCH=amd64
-fi
-
-if [ "$JAVA_HOME" = "" ]; then
-export JAVA_HOME=/usr/local/java
-fi
-
-if [ "$LD_LIBRARY_PATH" = "" ]; then
-export LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/$OS_ARCH/server:/usr/local/lib
-fi
-
-# If dev build set paths accordingly
-if [ -d $HADOOP_PREFIX/build ]; then
- export HADOOP_PREFIX=$HADOOP_PREFIX
- for f in ${HADOOP_PREFIX}/build/*.jar ; do
- export CLASSPATH=$CLASSPATH:$f
- done
- for f in $HADOOP_PREFIX/build/ivy/lib/hadoop-hdfs/common/*.jar ; do
- export CLASSPATH=$CLASSPATH:$f
- done
- export PATH=$HADOOP_PREFIX/build/contrib/fuse-dfs:$PATH
- export LD_LIBRARY_PATH=$HADOOP_PREFIX/build/c++/lib:$JAVA_HOME/jre/lib/$OS_ARCH/server
-fi
-
-fuse_dfs $@
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_file_handle.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_file_handle.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_file_handle.h
deleted file mode 100644
index 7f9346c..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_file_handle.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_FILE_HANDLE_H__
-#define __FUSE_FILE_HANDLE_H__
-
-#include <hdfs.h>
-#include <pthread.h>
-
-struct hdfsConn;
-
-/**
- *
- * dfs_fh_struct is passed around for open files. Fuse provides a hook (the context)
- * for storing file specific data.
- *
- * 2 Types of information:
- * a) a read buffer for performance reasons since fuse is typically called on 4K chunks only
- * b) the hdfs fs handle
- *
- */
-typedef struct dfs_fh_struct {
- hdfsFile hdfsFH;
- struct hdfsConn *conn;
- char *buf;
- tSize bufferSize; //what is the size of the buffer we have
- off_t buffersStartOffset; //where the buffer starts in the file
- pthread_mutex_t mutex;
-} dfs_fh;
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls.h
deleted file mode 100644
index d0d93e2..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-
-#ifndef __FUSE_IMPLS_H__
-#define __FUSE_IMPLS_H__
-
-#include <fuse.h>
-#include <syslog.h>
-
-#include "fuse_context_handle.h"
-
-/**
- * Implementations of the various fuse hooks.
- * All of these (should be) thread safe.
- *
- */
-
-int dfs_mkdir(const char *path, mode_t mode);
-int dfs_rename(const char *from, const char *to);
-int dfs_getattr(const char *path, struct stat *st);
-int dfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
- off_t offset, struct fuse_file_info *fi);
-int dfs_read(const char *path, char *buf, size_t size, off_t offset,
- struct fuse_file_info *fi);
-int dfs_statfs(const char *path, struct statvfs *st);
-int dfs_mkdir(const char *path, mode_t mode);
-int dfs_rename(const char *from, const char *to);
-int dfs_rmdir(const char *path);
-int dfs_unlink(const char *path);
-int dfs_utimens(const char *path, const struct timespec ts[2]);
-int dfs_chmod(const char *path, mode_t mode);
-int dfs_chown(const char *path, uid_t uid, gid_t gid);
-int dfs_open(const char *path, struct fuse_file_info *fi);
-int dfs_write(const char *path, const char *buf, size_t size,
- off_t offset, struct fuse_file_info *fi);
-int dfs_release (const char *path, struct fuse_file_info *fi);
-int dfs_mknod(const char *path, mode_t mode, dev_t rdev) ;
-int dfs_create(const char *path, mode_t mode, struct fuse_file_info *fi);
-int dfs_flush(const char *path, struct fuse_file_info *fi);
-int dfs_access(const char *path, int mask);
-int dfs_truncate(const char *path, off_t size);
-int dfs_symlink(const char *from, const char *to);
-
-#endif
-
-
-
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_access.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_access.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_access.c
deleted file mode 100644
index 033a1c3..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_access.c
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_connect.h"
-
-int dfs_access(const char *path, int mask)
-{
- TRACE1("access", path)
- assert(path != NULL);
- // TODO: HDFS-428
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_chmod.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_chmod.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_chmod.c
deleted file mode 100644
index 8c25f53..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_chmod.c
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_users.h"
-#include "fuse_connect.h"
-
-int dfs_chmod(const char *path, mode_t mode)
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- TRACE1("chmod", path)
- int ret = 0;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- assert(path);
- assert(dfs);
- assert('/' == *path);
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
-
- if (hdfsChmod(fs, path, (short)mode)) {
- ERROR("Could not chmod %s to %d", path, (int)mode);
- ret = (errno > 0) ? -errno : -EIO;
- goto cleanup;
- }
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
-
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_chown.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_chown.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_chown.c
deleted file mode 100644
index 2a6b61c..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_chown.c
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_users.h"
-#include "fuse_impls.h"
-#include "fuse_connect.h"
-
-#include <stdlib.h>
-
-int dfs_chown(const char *path, uid_t uid, gid_t gid)
-{
- struct hdfsConn *conn = NULL;
- int ret = 0;
- char *user = NULL;
- char *group = NULL;
-
- TRACE1("chown", path)
-
- // retrieve dfs specific data
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- // check params and the context var
- assert(path);
- assert(dfs);
- assert('/' == *path);
-
- if ((uid == -1) && (gid == -1)) {
- ret = 0;
- goto cleanup;
- }
- if (uid != -1) {
- user = getUsername(uid);
- if (NULL == user) {
- ERROR("Could not lookup the user id string %d",(int)uid);
- ret = -EIO;
- goto cleanup;
- }
- }
- if (gid != -1) {
- group = getGroup(gid);
- if (group == NULL) {
- ERROR("Could not lookup the group id string %d",(int)gid);
- ret = -EIO;
- goto cleanup;
- }
- }
-
- ret = fuseConnect(user, fuse_get_context(), &conn);
- if (ret) {
- fprintf(stderr, "fuseConnect: failed to open a libhdfs connection! "
- "error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
-
- if (hdfsChown(hdfsConnGetFs(conn), path, user, group)) {
- ret = errno;
- ERROR("Could not chown %s to %d:%d: error %d", path, (int)uid, gid, ret);
- ret = (ret > 0) ? -ret : -EIO;
- goto cleanup;
- }
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- free(user);
- free(group);
-
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_create.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_create.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_create.c
deleted file mode 100644
index 256e383..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_create.c
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-
-int dfs_create(const char *path, mode_t mode, struct fuse_file_info *fi)
-{
- TRACE1("create", path)
- fi->flags |= mode;
- return dfs_open(path, fi);
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_flush.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_flush.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_flush.c
deleted file mode 100644
index adb065b..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_flush.c
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_connect.h"
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_file_handle.h"
-
-int dfs_flush(const char *path, struct fuse_file_info *fi) {
- TRACE1("flush", path)
-
- // retrieve dfs specific data
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- // check params and the context var
- assert(path);
- assert(dfs);
- assert('/' == *path);
- assert(fi);
-
- if (NULL == (void*)fi->fh) {
- return 0;
- }
-
- // note that fuse calls flush on RO files too and hdfs does not like that and will return an error
- if (fi->flags & O_WRONLY) {
-
- dfs_fh *fh = (dfs_fh*)fi->fh;
- assert(fh);
- hdfsFile file_handle = (hdfsFile)fh->hdfsFH;
- assert(file_handle);
- if (hdfsFlush(hdfsConnGetFs(fh->conn), file_handle) != 0) {
- ERROR("Could not flush %lx for %s\n",(long)file_handle, path);
- return -EIO;
- }
- }
-
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_getattr.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_getattr.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_getattr.c
deleted file mode 100644
index 2e43518..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_getattr.c
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_stat_struct.h"
-#include "fuse_connect.h"
-
-int dfs_getattr(const char *path, struct stat *st)
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- int ret;
- hdfsFileInfo *info;
-
- TRACE1("getattr", path)
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
- assert(dfs);
- assert(path);
- assert(st);
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
-
- info = hdfsGetPathInfo(fs,path);
- if (NULL == info) {
- ret = -ENOENT;
- goto cleanup;
- }
- fill_stat_structure(&info[0], st);
-
- // setup hard link info - for a file it is 1 else num entries in a dir + 2 (for . and ..)
- if (info[0].mKind == kObjectKindDirectory) {
- int numEntries = 0;
- hdfsFileInfo *info = hdfsListDirectory(fs,path,&numEntries);
-
- if (info) {
- hdfsFreeFileInfo(info,numEntries);
- }
- st->st_nlink = numEntries + 2;
- } else {
- // not a directory
- st->st_nlink = 1;
- }
-
- // free the info pointer
- hdfsFreeFileInfo(info,1);
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_mkdir.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_mkdir.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_mkdir.c
deleted file mode 100644
index b05551f..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_mkdir.c
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_trash.h"
-#include "fuse_connect.h"
-
-int dfs_mkdir(const char *path, mode_t mode)
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
- int ret;
-
- TRACE1("mkdir", path)
-
- assert(path);
- assert(dfs);
- assert('/' == *path);
-
- if (is_protected(path)) {
- ERROR("HDFS trying to create directory %s", path);
- return -EACCES;
- }
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
-
- // In theory the create and chmod should be atomic.
-
- if (hdfsCreateDirectory(fs, path)) {
- ERROR("HDFS could not create directory %s", path);
- ret = (errno > 0) ? -errno : -EIO;
- goto cleanup;
- }
-
- if (hdfsChmod(fs, path, (short)mode)) {
- ERROR("Could not chmod %s to %d", path, (int)mode);
- ret = (errno > 0) ? -errno : -EIO;
- }
- ret = 0;
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_mknod.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_mknod.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_mknod.c
deleted file mode 100644
index c745cf1..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_mknod.c
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-
-int dfs_mknod(const char *path, mode_t mode, dev_t rdev)
-{
- TRACE1("mknod", path);
- DEBUG("dfs_mknod");
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_open.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_open.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_open.c
deleted file mode 100644
index ca670ce..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_open.c
+++ /dev/null
@@ -1,172 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_connect.h"
-#include "fuse_file_handle.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-/**
- * Given a set of FUSE flags, determine the libhdfs flags we need.
- *
- * This is complicated by two things:
- * 1. libhdfs doesn't support O_RDWR at all;
- * 2. when given O_WRONLY, libhdfs will truncate the file unless O_APPEND is
- * also given. In other words, there is an implicit O_TRUNC.
- *
- * Probably the next iteration of the libhdfs interface should not use the POSIX
- * flags at all, since, as you can see, they don't really match up very closely
- * to the POSIX meaning. However, for the time being, this is the API.
- *
- * @param fs The libhdfs object
- * @param path The path we're opening
- * @param flags The FUSE flags
- *
- * @return negative error code on failure; flags otherwise.
- */
-static int64_t get_hdfs_open_flags(hdfsFS fs, const char *path, int flags)
-{
- int64_t ret;
- hdfsFileInfo *info;
-
- if ((flags & O_ACCMODE) == O_RDONLY) {
- return O_RDONLY;
- }
- if (flags & O_TRUNC) {
- /* If we're opening for write or read/write, O_TRUNC means we should blow
- * away the file which is there and create our own file.
- * */
- return O_WRONLY;
- }
- info = hdfsGetPathInfo(fs, path);
- if (info) {
- if (info->mSize == 0) {
- // If the file has zero length, we shouldn't feel bad about blowing it
- // away.
- ret = O_WRONLY;
- } else if ((flags & O_ACCMODE) == O_RDWR) {
- // HACK: translate O_RDWR requests into O_RDONLY if the file already
- // exists and has non-zero length.
- ret = O_RDONLY;
- } else { // O_WRONLY
- // HACK: translate O_WRONLY requests into append if the file already
- // exists.
- ret = O_WRONLY | O_APPEND;
- }
- } else { // !info
- if (flags & O_CREAT) {
- ret = O_WRONLY;
- } else {
- ret = -ENOENT;
- }
- }
- if (info) {
- hdfsFreeFileInfo(info, 1);
- }
- return ret;
-}
-
-int dfs_open(const char *path, struct fuse_file_info *fi)
-{
- hdfsFS fs = NULL;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
- dfs_fh *fh = NULL;
- int mutexInit = 0, ret, flags = 0;
- int64_t flagRet;
-
- TRACE1("open", path)
-
- // check params and the context var
- assert(path);
- assert('/' == *path);
- assert(dfs);
-
- // retrieve dfs specific data
- fh = (dfs_fh*)calloc(1, sizeof (dfs_fh));
- if (!fh) {
- ERROR("Malloc of new file handle failed");
- ret = -EIO;
- goto error;
- }
- ret = fuseConnectAsThreadUid(&fh->conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto error;
- }
- fs = hdfsConnGetFs(fh->conn);
- flagRet = get_hdfs_open_flags(fs, path, fi->flags);
- if (flagRet < 0) {
- ret = -flagRet;
- goto error;
- }
- flags = flagRet;
- if ((fh->hdfsFH = hdfsOpenFile(fs, path, flags, 0, 0, 0)) == NULL) {
- ERROR("Could not open file %s (errno=%d)", path, errno);
- if (errno == 0 || errno == EINTERNAL) {
- ret = -EIO;
- goto error;
- }
- ret = -errno;
- goto error;
- }
-
- ret = pthread_mutex_init(&fh->mutex, NULL);
- if (ret) {
- fprintf(stderr, "dfs_open: error initializing mutex: error %d\n", ret);
- ret = -EIO;
- goto error;
- }
- mutexInit = 1;
-
- if ((flags & O_ACCMODE) == O_WRONLY) {
- fh->buf = NULL;
- } else {
- assert(dfs->rdbuffer_size > 0);
- fh->buf = (char*)malloc(dfs->rdbuffer_size * sizeof(char));
- if (NULL == fh->buf) {
- ERROR("Could not allocate memory for a read for file %s\n", path);
- ret = -EIO;
- goto error;
- }
- fh->buffersStartOffset = 0;
- fh->bufferSize = 0;
- }
- fi->fh = (uint64_t)fh;
- return 0;
-
-error:
- if (fh) {
- if (mutexInit) {
- pthread_mutex_destroy(&fh->mutex);
- }
- free(fh->buf);
- if (fh->hdfsFH) {
- hdfsCloseFile(fs, fh->hdfsFH);
- }
- if (fh->conn) {
- hdfsConnRelease(fh->conn);
- }
- free(fh);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_read.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_read.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_read.c
deleted file mode 100644
index feade45..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_read.c
+++ /dev/null
@@ -1,163 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_connect.h"
-#include "fuse_dfs.h"
-#include "fuse_file_handle.h"
-#include "fuse_impls.h"
-
-static size_t min(const size_t x, const size_t y) {
- return x < y ? x : y;
-}
-
-/**
- * dfs_read
- *
- * Reads from dfs or the open file's buffer. Note that fuse requires that
- * either the entire read be satisfied or the EOF is hit or direct_io is enabled
- *
- */
-int dfs_read(const char *path, char *buf, size_t size, off_t offset,
- struct fuse_file_info *fi)
-{
- TRACE1("read",path)
-
- // retrieve dfs specific data
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- // check params and the context var
- assert(dfs);
- assert(path);
- assert(buf);
- assert(offset >= 0);
- assert(size >= 0);
- assert(fi);
-
- dfs_fh *fh = (dfs_fh*)fi->fh;
- hdfsFS fs = hdfsConnGetFs(fh->conn);
-
- assert(fh != NULL);
- assert(fh->hdfsFH != NULL);
-
- // special case this as simplifies the rest of the logic to know the caller wanted > 0 bytes
- if (size == 0)
- return 0;
-
- // If size is bigger than the read buffer, then just read right into the user supplied buffer
- if ( size >= dfs->rdbuffer_size) {
- int num_read;
- size_t total_read = 0;
- while (size - total_read > 0 && (num_read = hdfsPread(fs, fh->hdfsFH, offset + total_read, buf + total_read, size - total_read)) > 0) {
- total_read += num_read;
- }
- // if there was an error before satisfying the current read, this logic declares it an error
- // and does not try to return any of the bytes read. Don't think it matters, so the code
- // is just being conservative.
- if (total_read < size && num_read < 0) {
- total_read = -EIO;
- }
- return total_read;
- }
-
- //
- // Critical section - protect from multiple reads in different threads accessing the read buffer
- // (no returns until end)
- //
-
- pthread_mutex_lock(&fh->mutex);
-
- // used only to check the postcondition of this function - namely that we satisfy
- // the entire read or EOF is hit.
- int isEOF = 0;
- int ret = 0;
-
- // check if the buffer is empty or
- // the read starts before the buffer starts or
- // the read ends after the buffer ends
-
- if (fh->bufferSize == 0 ||
- offset < fh->buffersStartOffset ||
- offset + size > fh->buffersStartOffset + fh->bufferSize)
- {
- // Read into the buffer from DFS
- int num_read = 0;
- size_t total_read = 0;
-
- while (dfs->rdbuffer_size - total_read > 0 &&
- (num_read = hdfsPread(fs, fh->hdfsFH, offset + total_read, fh->buf + total_read, dfs->rdbuffer_size - total_read)) > 0) {
- total_read += num_read;
- }
-
- // if there was an error before satisfying the current read, this logic declares it an error
- // and does not try to return any of the bytes read. Don't think it matters, so the code
- // is just being conservative.
- if (total_read < size && num_read < 0) {
- // invalidate the buffer
- fh->bufferSize = 0;
- ERROR("pread failed for %s with return code %d", path, (int)num_read);
- ret = -EIO;
- } else {
- // Either EOF, all read or read beyond size, but then there was an error
- fh->bufferSize = total_read;
- fh->buffersStartOffset = offset;
-
- if (dfs->rdbuffer_size - total_read > 0) {
- // assert(num_read == 0); this should be true since if num_read < 0 handled above.
- isEOF = 1;
- }
- }
- }
-
- //
- // NOTE on EOF, fh->bufferSize == 0 and ret = 0 ,so the logic for copying data into the caller's buffer is bypassed, and
- // the code returns 0 as required
- //
- if (ret == 0 && fh->bufferSize > 0) {
-
- assert(offset >= fh->buffersStartOffset);
- assert(fh->buf);
-
- const size_t bufferReadIndex = offset - fh->buffersStartOffset;
- assert(bufferReadIndex >= 0 && bufferReadIndex < fh->bufferSize);
-
- const size_t amount = min(fh->buffersStartOffset + fh->bufferSize - offset, size);
- assert(amount >= 0 && amount <= fh->bufferSize);
-
- const char *offsetPtr = fh->buf + bufferReadIndex;
- assert(offsetPtr >= fh->buf);
- assert(offsetPtr + amount <= fh->buf + fh->bufferSize);
-
- memcpy(buf, offsetPtr, amount);
-
- ret = amount;
- }
-
- //
- // Critical section end
- //
- pthread_mutex_unlock(&fh->mutex);
-
- // fuse requires the below and the code should guarantee this assertion
- // 3 cases on return:
- // 1. entire read satisfied
- // 2. partial read and isEOF - including 0 size read
- // 3. error
- assert(ret == size || isEOF || ret < 0);
-
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_readdir.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_readdir.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_readdir.c
deleted file mode 100644
index 326f573..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_readdir.c
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_stat_struct.h"
-#include "fuse_connect.h"
-
-int dfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
- off_t offset, struct fuse_file_info *fi)
-{
- int ret;
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- TRACE1("readdir", path)
-
- assert(dfs);
- assert(path);
- assert(buf);
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
-
- // Read dirents. Calling a variant that just returns the final path
- // component (HDFS-975) would save us from parsing it out below.
- int numEntries = 0;
- hdfsFileInfo *info = hdfsListDirectory(fs, path, &numEntries);
-
- // NULL means either the directory doesn't exist or maybe IO error.
- if (NULL == info) {
- ret = (errno > 0) ? -errno : -ENOENT;
- goto cleanup;
- }
-
- int i ;
- for (i = 0; i < numEntries; i++) {
- if (NULL == info[i].mName) {
- ERROR("Path %s info[%d].mName is NULL", path, i);
- continue;
- }
-
- struct stat st;
- fill_stat_structure(&info[i], &st);
-
- // Find the final path component
- const char *str = strrchr(info[i].mName, '/');
- if (NULL == str) {
- ERROR("Invalid URI %s", info[i].mName);
- continue;
- }
- str++;
-
- // pack this entry into the fuse buffer
- int res = 0;
- if ((res = filler(buf,str,&st,0)) != 0) {
- ERROR("Readdir filler failed: %d\n",res);
- }
- }
-
- // insert '.' and '..'
- const char *const dots [] = { ".",".."};
- for (i = 0 ; i < 2 ; i++)
- {
- struct stat st;
- memset(&st, 0, sizeof(struct stat));
-
- // set to 0 to indicate not supported for directory because we cannot (efficiently) get this info for every subdirectory
- st.st_nlink = 0;
-
- // setup stat size and acl meta data
- st.st_size = 512;
- st.st_blksize = 512;
- st.st_blocks = 1;
- st.st_mode = (S_IFDIR | 0777);
- st.st_uid = default_id;
- st.st_gid = default_id;
- // todo fix below times
- st.st_atime = 0;
- st.st_mtime = 0;
- st.st_ctime = 0;
-
- const char *const str = dots[i];
-
- // flatten the info using fuse's function into a buffer
- int res = 0;
- if ((res = filler(buf,str,&st,0)) != 0) {
- ERROR("Readdir filler failed: %d\n",res);
- }
- }
- // free the info pointers
- hdfsFreeFileInfo(info,numEntries);
- ret = 0;
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_release.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_release.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_release.c
deleted file mode 100644
index 0316de6..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_release.c
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_file_handle.h"
-#include "fuse_connect.h"
-
-#include <stdlib.h>
-
-/**
- * release a fuse_file_info structure.
- *
- * When this function is invoked, there are no more references to our
- * fuse_file_info structure that exist anywhere. So there is no need for
- * locking to protect this structure here.
- *
- * Another thread could open() the same file, and get a separate, different file
- * descriptor with a different, separate fuse_file_info structure. In HDFS,
- * this results in one writer winning and overwriting everything the other
- * writer has done.
- */
-
-int dfs_release (const char *path, struct fuse_file_info *fi) {
- TRACE1("release", path)
-
- // retrieve dfs specific data
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- // check params and the context var
- assert(path);
- assert(dfs);
- assert('/' == *path);
-
- int ret = 0;
- dfs_fh *fh = (dfs_fh*)fi->fh;
- assert(fh);
- hdfsFile file_handle = (hdfsFile)fh->hdfsFH;
- if (NULL != file_handle) {
- if (hdfsCloseFile(hdfsConnGetFs(fh->conn), file_handle) != 0) {
- ERROR("Could not close handle %ld for %s\n",(long)file_handle, path);
- ret = -EIO;
- }
- }
- free(fh->buf);
- hdfsConnRelease(fh->conn);
- pthread_mutex_destroy(&fh->mutex);
- free(fh);
- fi->fh = 0;
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_rename.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_rename.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_rename.c
deleted file mode 100644
index ad7c7e5..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_rename.c
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_trash.h"
-#include "fuse_connect.h"
-
-int dfs_rename(const char *from, const char *to)
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
- int ret;
-
- TRACE1("rename", from)
-
- // check params and the context var
- assert(from);
- assert(to);
- assert(dfs);
-
- assert('/' == *from);
- assert('/' == *to);
-
- if (is_protected(from) || is_protected(to)) {
- ERROR("Could not rename %s to %s", from, to);
- return -EACCES;
- }
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
- if (hdfsRename(fs, from, to)) {
- ERROR("Rename %s to %s failed", from, to);
- ret = (errno > 0) ? -errno : -EIO;
- goto cleanup;
- }
- ret = 0;
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_rmdir.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_rmdir.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_rmdir.c
deleted file mode 100644
index 493807f..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_rmdir.c
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_trash.h"
-#include "fuse_connect.h"
-
-extern const char *const TrashPrefixDir;
-
-int dfs_rmdir(const char *path)
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- int ret;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
- int numEntries = 0;
- hdfsFileInfo *info = NULL;
-
- TRACE1("rmdir", path)
-
- assert(path);
- assert(dfs);
- assert('/' == *path);
-
- if (is_protected(path)) {
- ERROR("Trying to delete protected directory %s", path);
- ret = -EACCES;
- goto cleanup;
- }
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
- info = hdfsListDirectory(fs, path, &numEntries);
- if (numEntries) {
- ret = -ENOTEMPTY;
- goto cleanup;
- }
-
- if (hdfsDeleteWithTrash(fs, path, dfs->usetrash)) {
- ERROR("Error trying to delete directory %s", path);
- ret = -EIO;
- goto cleanup;
- }
- ret = 0;
-
-cleanup:
- if (info) {
- hdfsFreeFileInfo(info, numEntries);
- }
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-}
[13/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_web.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_web.c b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_web.c
deleted file mode 100644
index 86b4faf..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_web.c
+++ /dev/null
@@ -1,1538 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include "exception.h"
-#include "hdfs.h"
-#include "hdfs_http_client.h"
-#include "hdfs_http_query.h"
-#include "hdfs_json_parser.h"
-#include "jni_helper.h"
-
-#define HADOOP_HDFS_CONF "org/apache/hadoop/hdfs/HdfsConfiguration"
-#define HADOOP_NAMENODE "org/apache/hadoop/hdfs/server/namenode/NameNode"
-#define JAVA_INETSOCKETADDRESS "java/net/InetSocketAddress"
-
-struct hdfsBuilder {
- int forceNewInstance;
- const char *nn;
- tPort port;
- const char *kerbTicketCachePath;
- const char *userName;
-};
-
-/**
- * The information required for accessing webhdfs,
- * including the network address of the namenode and the user name
- *
- * Unlike the string in hdfsBuilder, the strings in this structure are
- * dynamically allocated. This structure will not be freed until we disconnect
- * from HDFS.
- */
-struct hdfs_internal {
- char *nn;
- tPort port;
- char *userName;
-
- /**
- * Working directory -- stored with a trailing slash.
- */
- char *workingDir;
-};
-
-/**
- * The 'file-handle' to a file in hdfs.
- */
-struct hdfsFile_internal {
- struct webhdfsFileHandle* file;
- enum hdfsStreamType type; /* INPUT or OUTPUT */
- int flags; /* Flag indicate read/create/append etc. */
- tOffset offset; /* Current offset position in the file */
-};
-
-/**
- * Create, initialize and return a webhdfsBuffer
- */
-static int initWebHdfsBuffer(struct webhdfsBuffer **webhdfsBuffer)
-{
- int ret = 0;
- struct webhdfsBuffer *buffer = calloc(1, sizeof(struct webhdfsBuffer));
- if (!buffer) {
- fprintf(stderr,
- "ERROR: fail to allocate memory for webhdfsBuffer.\n");
- return ENOMEM;
- }
- ret = pthread_mutex_init(&buffer->writeMutex, NULL);
- if (ret) {
- fprintf(stderr, "ERROR: fail in pthread_mutex_init for writeMutex "
- "in initWebHdfsBuffer, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- goto done;
- }
- ret = pthread_cond_init(&buffer->newwrite_or_close, NULL);
- if (ret) {
- fprintf(stderr,
- "ERROR: fail in pthread_cond_init for newwrite_or_close "
- "in initWebHdfsBuffer, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- goto done;
- }
- ret = pthread_cond_init(&buffer->transfer_finish, NULL);
- if (ret) {
- fprintf(stderr,
- "ERROR: fail in pthread_cond_init for transfer_finish "
- "in initWebHdfsBuffer, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- goto done;
- }
-
-done:
- if (ret) {
- free(buffer);
- return ret;
- }
- *webhdfsBuffer = buffer;
- return 0;
-}
-
-/**
- * Reset the webhdfsBuffer. This is used in a block way
- * when hdfsWrite is called with a new buffer to write.
- * The writing thread in libcurl will be waken up to continue writing,
- * and the caller of this function is blocked waiting for writing to finish.
- *
- * @param wb The handle of the webhdfsBuffer
- * @param buffer The buffer provided by user to write
- * @param length The length of bytes to write
- * @return Updated webhdfsBuffer.
- */
-static struct webhdfsBuffer *resetWebhdfsBuffer(struct webhdfsBuffer *wb,
- const char *buffer, size_t length)
-{
- if (buffer && length > 0) {
- pthread_mutex_lock(&wb->writeMutex);
- wb->wbuffer = buffer;
- wb->offset = 0;
- wb->remaining = length;
- pthread_cond_signal(&wb->newwrite_or_close);
- while (wb->remaining != 0) {
- pthread_cond_wait(&wb->transfer_finish, &wb->writeMutex);
- }
- pthread_mutex_unlock(&wb->writeMutex);
- }
- return wb;
-}
-
-/**
- * Free the webhdfsBuffer and destroy its pthread conditions/mutex
- * @param buffer The webhdfsBuffer to free
- */
-static void freeWebhdfsBuffer(struct webhdfsBuffer *buffer)
-{
- int ret = 0;
- if (buffer) {
- ret = pthread_cond_destroy(&buffer->newwrite_or_close);
- if (ret) {
- fprintf(stderr,
- "WARN: fail in pthread_cond_destroy for newwrite_or_close "
- "in freeWebhdfsBuffer, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- errno = ret;
- }
- ret = pthread_cond_destroy(&buffer->transfer_finish);
- if (ret) {
- fprintf(stderr,
- "WARN: fail in pthread_cond_destroy for transfer_finish "
- "in freeWebhdfsBuffer, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- errno = ret;
- }
- ret = pthread_mutex_destroy(&buffer->writeMutex);
- if (ret) {
- fprintf(stderr,
- "WARN: fail in pthread_mutex_destroy for writeMutex "
- "in freeWebhdfsBuffer, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- errno = ret;
- }
- free(buffer);
- buffer = NULL;
- }
-}
-
-/**
- * To free the webhdfsFileHandle, which includes a webhdfsBuffer and strings
- * @param handle The webhdfsFileHandle to free
- */
-static void freeWebFileHandle(struct webhdfsFileHandle * handle)
-{
- if (!handle)
- return;
- freeWebhdfsBuffer(handle->uploadBuffer);
- free(handle->datanode);
- free(handle->absPath);
- free(handle);
-}
-
-static const char *maybeNull(const char *str)
-{
- return str ? str : "(NULL)";
-}
-
-/** To print a hdfsBuilder as string */
-static const char *hdfsBuilderToStr(const struct hdfsBuilder *bld,
- char *buf, size_t bufLen)
-{
- int strlength = snprintf(buf, bufLen, "nn=%s, port=%d, "
- "kerbTicketCachePath=%s, userName=%s",
- maybeNull(bld->nn), bld->port,
- maybeNull(bld->kerbTicketCachePath), maybeNull(bld->userName));
- if (strlength < 0 || strlength >= bufLen) {
- fprintf(stderr, "failed to print a hdfsBuilder as string.\n");
- return NULL;
- }
- return buf;
-}
-
-/**
- * Free a hdfs_internal handle
- * @param fs The hdfs_internal handle to free
- */
-static void freeWebHdfsInternal(struct hdfs_internal *fs)
-{
- if (fs) {
- free(fs->nn);
- free(fs->userName);
- free(fs->workingDir);
- }
-}
-
-struct hdfsBuilder *hdfsNewBuilder(void)
-{
- struct hdfsBuilder *bld = calloc(1, sizeof(struct hdfsBuilder));
- if (!bld) {
- errno = ENOMEM;
- return NULL;
- }
- return bld;
-}
-
-void hdfsFreeBuilder(struct hdfsBuilder *bld)
-{
- free(bld);
-}
-
-void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld)
-{
- // We don't cache instances in libwebhdfs, so this is not applicable.
-}
-
-void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn)
-{
- if (bld) {
- bld->nn = nn;
- }
-}
-
-void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port)
-{
- if (bld) {
- bld->port = port;
- }
-}
-
-void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName)
-{
- if (bld) {
- bld->userName = userName;
- }
-}
-
-void hdfsBuilderSetKerbTicketCachePath(struct hdfsBuilder *bld,
- const char *kerbTicketCachePath)
-{
- if (bld) {
- bld->kerbTicketCachePath = kerbTicketCachePath;
- }
-}
-
-hdfsFS hdfsConnectAsUser(const char* nn, tPort port, const char *user)
-{
- struct hdfsBuilder* bld = hdfsNewBuilder();
- if (!bld) {
- return NULL;
- }
- hdfsBuilderSetNameNode(bld, nn);
- hdfsBuilderSetNameNodePort(bld, port);
- hdfsBuilderSetUserName(bld, user);
- return hdfsBuilderConnect(bld);
-}
-
-hdfsFS hdfsConnect(const char* nn, tPort port)
-{
- return hdfsConnectAsUser(nn, port, NULL);
-}
-
-hdfsFS hdfsConnectNewInstance(const char* nn, tPort port)
-{
- return hdfsConnect(nn, port);
-}
-
-hdfsFS hdfsConnectAsUserNewInstance(const char* host, tPort port,
- const char *user)
-{
- struct hdfsBuilder *bld = hdfsNewBuilder();
- if (!bld)
- return NULL;
- hdfsBuilderSetNameNode(bld, host);
- hdfsBuilderSetNameNodePort(bld, port);
- hdfsBuilderSetUserName(bld, user);
- hdfsBuilderSetForceNewInstance(bld);
- return hdfsBuilderConnect(bld);
-}
-
-/**
- * To retrieve the default configuration value for NameNode's hostName and port
- * TODO: This function currently is using JNI,
- * we need to do this without using JNI (HDFS-3917)
- *
- * @param bld The hdfsBuilder handle
- * @param port Used to get the default value for NameNode's port
- * @param nn Used to get the default value for NameNode's hostName
- * @return 0 for success and non-zero value for failure
- */
-static int retrieveDefaults(const struct hdfsBuilder *bld, tPort *port,
- char **nn)
-{
- JNIEnv *env = 0;
- jobject jHDFSConf = NULL, jAddress = NULL;
- jstring jHostName = NULL;
- jvalue jVal;
- jthrowable jthr = NULL;
- int ret = 0;
- char buf[512];
-
- env = getJNIEnv();
- if (!env) {
- return EINTERNAL;
- }
-
- jthr = constructNewObjectOfClass(env, &jHDFSConf, HADOOP_HDFS_CONF, "()V");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
-
- jthr = invokeMethod(env, &jVal, STATIC, NULL,
- HADOOP_NAMENODE, "getHttpAddress",
- "(Lorg/apache/hadoop/conf/Configuration;)Ljava/net/InetSocketAddress;",
- jHDFSConf);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jAddress = jVal.l;
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jAddress,
- JAVA_INETSOCKETADDRESS, "getPort", "()I");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- *port = jVal.i;
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jAddress,
- JAVA_INETSOCKETADDRESS,
- "getHostName", "()Ljava/lang/String;");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jHostName = jVal.l;
- jthr = newCStr(env, jHostName, nn);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
-
-done:
- destroyLocalReference(env, jHDFSConf);
- destroyLocalReference(env, jAddress);
- destroyLocalReference(env, jHostName);
- return ret;
-}
-
-hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld)
-{
- struct hdfs_internal *fs = NULL;
- int ret = 0;
-
- if (!bld) {
- ret = EINVAL;
- goto done;
- }
- if (bld->nn == NULL) {
- // In the JNI version of libhdfs this returns a LocalFileSystem.
- ret = ENOTSUP;
- goto done;
- }
-
- fs = calloc(1, sizeof(*fs));
- if (!fs) {
- ret = ENOMEM;
- goto done;
- }
- // If the namenode is "default" and/or the port of namenode is 0,
- // get the default namenode/port
- if (bld->port == 0 || !strcasecmp("default", bld->nn)) {
- ret = retrieveDefaults(bld, &fs->port, &fs->nn);
- if (ret)
- goto done;
- } else {
- fs->port = bld->port;
- fs->nn = strdup(bld->nn);
- if (!fs->nn) {
- ret = ENOMEM;
- goto done;
- }
- }
- if (bld->userName) {
- // userName may be NULL
- fs->userName = strdup(bld->userName);
- if (!fs->userName) {
- ret = ENOMEM;
- goto done;
- }
- }
- // The working directory starts out as root.
- fs->workingDir = strdup("/");
- if (!fs->workingDir) {
- ret = ENOMEM;
- goto done;
- }
- // For debug
- fprintf(stderr, "namenode: %s:%d\n", bld->nn, bld->port);
-
-done:
- free(bld);
- if (ret) {
- freeWebHdfsInternal(fs);
- errno = ret;
- return NULL;
- }
- return fs;
-}
-
-int hdfsDisconnect(hdfsFS fs)
-{
- if (fs == NULL) {
- errno = EINVAL;
- return -1;
- }
- freeWebHdfsInternal(fs);
- return 0;
-}
-
-/**
- * Based on the working directory stored in hdfsFS,
- * generate the absolute path for the given path
- *
- * @param fs The hdfsFS handle which stores the current working directory
- * @param path The given path which may not be an absolute path
- * @param absPath To hold generated absolute path for the given path
- * @return 0 on success, non-zero value indicating error
- */
-static int getAbsolutePath(hdfsFS fs, const char *path, char **absPath)
-{
- char *tempPath = NULL;
- size_t absPathLen;
- int strlength;
-
- if (path[0] == '/') {
- // Path is already absolute.
- tempPath = strdup(path);
- if (!tempPath) {
- return ENOMEM;
- }
- *absPath = tempPath;
- return 0;
- }
- // Prepend the workingDir to the path.
- absPathLen = strlen(fs->workingDir) + strlen(path) + 1;
- tempPath = malloc(absPathLen);
- if (!tempPath) {
- return ENOMEM;
- }
- strlength = snprintf(tempPath, absPathLen, "%s%s", fs->workingDir, path);
- if (strlength < 0 || strlength >= absPathLen) {
- free(tempPath);
- return EIO;
- }
- *absPath = tempPath;
- return 0;
-}
-
-int hdfsCreateDirectory(hdfsFS fs, const char* path)
-{
- char *url = NULL, *absPath = NULL;
- struct Response *resp = NULL;
- int ret = 0;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
- ret = getAbsolutePath(fs, path, &absPath);
- if (ret) {
- goto done;
- }
- ret = createUrlForMKDIR(fs->nn, fs->port, absPath, fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchMKDIR(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseMKDIR(resp->body->content);
-done:
- freeResponse(resp);
- free(url);
- free(absPath);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsChmod(hdfsFS fs, const char* path, short mode)
-{
- char *absPath = NULL, *url = NULL;
- struct Response *resp = NULL;
- int ret = 0;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
- ret = getAbsolutePath(fs, path, &absPath);
- if (ret) {
- goto done;
- }
- ret = createUrlForCHMOD(fs->nn, fs->port, absPath, (int) mode,
- fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchCHMOD(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseCHMOD(resp->header->content, resp->body->content);
-done:
- freeResponse(resp);
- free(absPath);
- free(url);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsChown(hdfsFS fs, const char* path, const char *owner, const char *group)
-{
- int ret = 0;
- char *absPath = NULL, *url = NULL;
- struct Response *resp = NULL;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
-
- ret = getAbsolutePath(fs, path, &absPath);
- if (ret) {
- goto done;
- }
- ret = createUrlForCHOWN(fs->nn, fs->port, absPath,
- owner, group, fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchCHOWN(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseCHOWN(resp->header->content, resp->body->content);
-done:
- freeResponse(resp);
- free(absPath);
- free(url);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath)
-{
- char *oldAbsPath = NULL, *newAbsPath = NULL, *url = NULL;
- int ret = 0;
- struct Response *resp = NULL;
-
- if (fs == NULL || oldPath == NULL || newPath == NULL) {
- ret = EINVAL;
- goto done;
- }
- ret = getAbsolutePath(fs, oldPath, &oldAbsPath);
- if (ret) {
- goto done;
- }
- ret = getAbsolutePath(fs, newPath, &newAbsPath);
- if (ret) {
- goto done;
- }
- ret = createUrlForRENAME(fs->nn, fs->port, oldAbsPath,
- newAbsPath, fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchRENAME(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseRENAME(resp->body->content);
-done:
- freeResponse(resp);
- free(oldAbsPath);
- free(newAbsPath);
- free(url);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-/**
- * Get the file status for a given path.
- *
- * @param fs hdfsFS handle containing
- * NameNode hostName/port information
- * @param path Path for file
- * @param printError Whether or not to print out error information
- * (mainly remote FileNotFoundException)
- * @return File information for the given path
- */
-static hdfsFileInfo *hdfsGetPathInfoImpl(hdfsFS fs, const char* path,
- int printError)
-{
- char *absPath = NULL;
- char *url=NULL;
- struct Response *resp = NULL;
- int ret = 0;
- hdfsFileInfo *fileInfo = NULL;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
- ret = getAbsolutePath(fs, path, &absPath);
- if (ret) {
- goto done;
- }
- fileInfo = (hdfsFileInfo *) calloc(1, sizeof(hdfsFileInfo));
- if (!fileInfo) {
- ret = ENOMEM;
- goto done;
- }
- fileInfo->mKind = kObjectKindFile;
-
- ret = createUrlForGetFileStatus(fs->nn, fs->port, absPath,
- fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchGFS(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseGFS(resp->body->content, fileInfo, printError);
-
-done:
- freeResponse(resp);
- free(absPath);
- free(url);
- if (ret == 0) {
- return fileInfo;
- } else {
- free(fileInfo);
- errno = ret;
- return NULL;
- }
-}
-
-hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path)
-{
- return hdfsGetPathInfoImpl(fs, path, 1);
-}
-
-hdfsFileInfo *hdfsListDirectory(hdfsFS fs, const char* path, int *numEntries)
-{
- char *url = NULL, *absPath = NULL;
- struct Response *resp = NULL;
- int ret = 0;
- hdfsFileInfo *fileInfo = NULL;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
- ret = getAbsolutePath(fs, path, &absPath);
- if (ret) {
- goto done;
- }
- fileInfo = calloc(1, sizeof(*fileInfo));
- if (!fileInfo) {
- ret = ENOMEM;
- goto done;
- }
-
- ret = createUrlForLS(fs->nn, fs->port, absPath, fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchLS(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseLS(resp->body->content, &fileInfo, numEntries);
-
-done:
- freeResponse(resp);
- free(absPath);
- free(url);
- if (ret == 0) {
- return fileInfo;
- } else {
- errno = ret;
- return NULL;
- }
-}
-
-int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication)
-{
- char *url = NULL, *absPath = NULL;
- struct Response *resp = NULL;
- int ret = 0;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
- ret = getAbsolutePath(fs, path, &absPath);
- if (ret) {
- goto done;
- }
-
- ret = createUrlForSETREPLICATION(fs->nn, fs->port, absPath,
- replication, fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchSETREPLICATION(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseSETREPLICATION(resp->body->content);
-done:
- freeResponse(resp);
- free(absPath);
- free(url);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries)
-{
- int i;
- for (i = 0; i < numEntries; ++i) {
- free(hdfsFileInfo[i].mName);
- free(hdfsFileInfo[i].mOwner);
- free(hdfsFileInfo[i].mGroup);
- }
- free(hdfsFileInfo);
-}
-
-int hdfsDelete(hdfsFS fs, const char* path, int recursive)
-{
- char *url = NULL, *absPath = NULL;
- struct Response *resp = NULL;
- int ret = 0;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
- ret = getAbsolutePath(fs, path, &absPath);
- if (ret) {
- goto done;
- }
-
- ret = createUrlForDELETE(fs->nn, fs->port, absPath,
- recursive, fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchDELETE(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseDELETE(resp->body->content);
-done:
- freeResponse(resp);
- free(absPath);
- free(url);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime)
-{
- char *url = NULL, *absPath = NULL;
- struct Response *resp = NULL;
- int ret = 0;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
- ret = getAbsolutePath(fs, path, &absPath);
- if (ret) {
- goto done;
- }
-
- ret = createUrlForUTIMES(fs->nn, fs->port, absPath, mtime, atime,
- fs->userName, &url);
- if (ret) {
- goto done;
- }
- ret = launchUTIMES(url, &resp);
- if (ret) {
- goto done;
- }
- ret = parseUTIMES(resp->header->content, resp->body->content);
-done:
- freeResponse(resp);
- free(absPath);
- free(url);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsExists(hdfsFS fs, const char *path)
-{
- hdfsFileInfo *fileInfo = hdfsGetPathInfoImpl(fs, path, 0);
- if (!fileInfo) {
- // (errno will have been set by hdfsGetPathInfo)
- return -1;
- }
- hdfsFreeFileInfo(fileInfo, 1);
- return 0;
-}
-
-/**
- * The information hold by the thread which writes data to hdfs through http
- */
-typedef struct {
- char *url; /* the url of the target datanode for writing*/
- struct webhdfsBuffer *uploadBuffer; /* buffer storing data to write */
- int flags; /* flag indicating writing mode: create or append */
- struct Response *resp; /* response from the target datanode */
-} threadData;
-
-/**
- * Free the threadData struct instance,
- * including the response and url contained in it
- * @param data The threadData instance to free
- */
-static void freeThreadData(threadData *data)
-{
- if (data) {
- if (data->url) {
- free(data->url);
- }
- if (data->resp) {
- freeResponse(data->resp);
- }
- // The uploadBuffer would be freed by freeWebFileHandle()
- free(data);
- data = NULL;
- }
-}
-
-/**
- * The action of the thread that writes data to
- * the target datanode for hdfsWrite.
- * The writing can be either create or append, which is specified by flag
- */
-static void *writeThreadOperation(void *v)
-{
- int ret = 0;
- threadData *data = v;
- if (data->flags & O_APPEND) {
- ret = launchDnAPPEND(data->url, data->uploadBuffer, &(data->resp));
- } else {
- ret = launchDnWRITE(data->url, data->uploadBuffer, &(data->resp));
- }
- if (ret) {
- fprintf(stderr, "Failed to write to datanode %s, <%d>: %s.\n",
- data->url, ret, hdfs_strerror(ret));
- }
- return data;
-}
-
-/**
- * Free the memory associated with a webHDFS file handle.
- *
- * No other resources will be freed.
- *
- * @param file The webhdfs file handle
- */
-static void freeFileInternal(hdfsFile file)
-{
- if (!file)
- return;
- freeWebFileHandle(file->file);
- free(file);
-}
-
-/**
- * Helper function for opening a file for OUTPUT.
- *
- * As part of the open process for OUTPUT files, we have to connect to the
- * NameNode and get the URL of the corresponding DataNode.
- * We also create a background thread here for doing I/O.
- *
- * @param webhandle The webhandle being opened
- * @return 0 on success; error code otherwise
- */
-static int hdfsOpenOutputFileImpl(hdfsFS fs, hdfsFile file)
-{
- struct webhdfsFileHandle *webhandle = file->file;
- struct Response *resp = NULL;
- int append, ret = 0;
- char *nnUrl = NULL, *dnUrl = NULL;
- threadData *data = NULL;
-
- ret = initWebHdfsBuffer(&webhandle->uploadBuffer);
- if (ret) {
- goto done;
- }
- append = file->flags & O_APPEND;
- if (!append) {
- // If we're not appending, send a create request to the NN
- ret = createUrlForNnWRITE(fs->nn, fs->port, webhandle->absPath,
- fs->userName, webhandle->replication,
- webhandle->blockSize, &nnUrl);
- } else {
- ret = createUrlForNnAPPEND(fs->nn, fs->port, webhandle->absPath,
- fs->userName, &nnUrl);
- }
- if (ret) {
- fprintf(stderr, "Failed to create the url connecting to namenode "
- "for file creation/appending, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- goto done;
- }
- if (!append) {
- ret = launchNnWRITE(nnUrl, &resp);
- } else {
- ret = launchNnAPPEND(nnUrl, &resp);
- }
- if (ret) {
- fprintf(stderr, "fail to get the response from namenode for "
- "file creation/appending, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- goto done;
- }
- if (!append) {
- ret = parseNnWRITE(resp->header->content, resp->body->content);
- } else {
- ret = parseNnAPPEND(resp->header->content, resp->body->content);
- }
- if (ret) {
- fprintf(stderr, "fail to parse the response from namenode for "
- "file creation/appending, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- goto done;
- }
- ret = parseDnLoc(resp->header->content, &dnUrl);
- if (ret) {
- fprintf(stderr, "fail to get the datanode url from namenode "
- "for file creation/appending, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- goto done;
- }
- //store the datanode url in the file handle
- webhandle->datanode = strdup(dnUrl);
- if (!webhandle->datanode) {
- ret = ENOMEM;
- goto done;
- }
- //create a new thread for performing the http transferring
- data = calloc(1, sizeof(*data));
- if (!data) {
- ret = ENOMEM;
- goto done;
- }
- data->url = strdup(dnUrl);
- if (!data->url) {
- ret = ENOMEM;
- goto done;
- }
- data->flags = file->flags;
- data->uploadBuffer = webhandle->uploadBuffer;
- ret = pthread_create(&webhandle->connThread, NULL,
- writeThreadOperation, data);
- if (ret) {
- fprintf(stderr, "ERROR: failed to create the writing thread "
- "in hdfsOpenOutputFileImpl, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- goto done;
- }
- webhandle->uploadBuffer->openFlag = 1;
-
-done:
- freeResponse(resp);
- free(nnUrl);
- free(dnUrl);
- if (ret) {
- errno = ret;
- if (data) {
- free(data->url);
- free(data);
- }
- }
- return ret;
-}
-
-hdfsFile hdfsOpenFile(hdfsFS fs, const char* path, int flags,
- int bufferSize, short replication, tSize blockSize)
-{
- int ret = 0;
- int accmode = flags & O_ACCMODE;
- struct webhdfsFileHandle *webhandle = NULL;
- hdfsFile file = NULL;
-
- if (fs == NULL || path == NULL) {
- ret = EINVAL;
- goto done;
- }
- if (accmode == O_RDWR) {
- // TODO: the original libhdfs has very hackish support for this; should
- // we do the same? It would actually be a lot easier in libwebhdfs
- // since the protocol isn't connection-oriented.
- fprintf(stderr, "ERROR: cannot open an hdfs file in O_RDWR mode\n");
- ret = ENOTSUP;
- goto done;
- }
- if ((flags & O_CREAT) && (flags & O_EXCL)) {
- fprintf(stderr,
- "WARN: hdfs does not truly support O_CREATE && O_EXCL\n");
- }
- file = calloc(1, sizeof(struct hdfsFile_internal));
- if (!file) {
- ret = ENOMEM;
- goto done;
- }
- file->flags = flags;
- file->type = accmode == O_RDONLY ? INPUT : OUTPUT;
- file->offset = 0;
- webhandle = calloc(1, sizeof(struct webhdfsFileHandle));
- if (!webhandle) {
- ret = ENOMEM;
- goto done;
- }
- webhandle->bufferSize = bufferSize;
- webhandle->replication = replication;
- webhandle->blockSize = blockSize;
- ret = getAbsolutePath(fs, path, &webhandle->absPath);
- if (ret) {
- goto done;
- }
- file->file = webhandle;
- // If open for write/append,
- // open and keep the connection with the target datanode for writing
- if (file->type == OUTPUT) {
- ret = hdfsOpenOutputFileImpl(fs, file);
- if (ret) {
- goto done;
- }
- }
-
-done:
- if (ret) {
- if (file) {
- freeFileInternal(file); // Also frees webhandle
- } else {
- freeWebFileHandle(webhandle);
- }
- errno = ret;
- return NULL;
- }
- return file;
-}
-
-int hdfsTruncateFile(hdfsFS fs, const char* path, tOffset newlength)
-{
- errno = ENOTSUP;
- return -1;
-}
-
-tSize hdfsWrite(hdfsFS fs, hdfsFile file, const void* buffer, tSize length)
-{
- if (length == 0) {
- return 0;
- }
- if (fs == NULL || file == NULL || file->type != OUTPUT || length < 0) {
- errno = EBADF;
- return -1;
- }
-
- struct webhdfsFileHandle *wfile = file->file;
- if (wfile->uploadBuffer && wfile->uploadBuffer->openFlag) {
- resetWebhdfsBuffer(wfile->uploadBuffer, buffer, length);
- return length;
- } else {
- fprintf(stderr,
- "Error: have not opened the file %s for writing yet.\n",
- wfile->absPath);
- errno = EBADF;
- return -1;
- }
-}
-
-int hdfsCloseFile(hdfsFS fs, hdfsFile file)
-{
- void *respv = NULL;
- threadData *tdata = NULL;
- int ret = 0;
- struct webhdfsFileHandle *wfile = NULL;
-
- if (file->type == OUTPUT) {
- wfile = file->file;
- pthread_mutex_lock(&(wfile->uploadBuffer->writeMutex));
- wfile->uploadBuffer->closeFlag = 1;
- pthread_cond_signal(&wfile->uploadBuffer->newwrite_or_close);
- pthread_mutex_unlock(&(wfile->uploadBuffer->writeMutex));
-
- // Waiting for the writing thread to terminate
- ret = pthread_join(wfile->connThread, &respv);
- if (ret) {
- fprintf(stderr, "Error when pthread_join in hdfsClose, <%d>: %s.\n",
- ret, hdfs_strerror(ret));
- }
- // Parse the response
- tdata = respv;
- if (!tdata || !(tdata->resp)) {
- fprintf(stderr,
- "ERROR: response from the writing thread is NULL.\n");
- ret = EIO;
- }
- if (file->flags & O_APPEND) {
- ret = parseDnAPPEND(tdata->resp->header->content,
- tdata->resp->body->content);
- } else {
- ret = parseDnWRITE(tdata->resp->header->content,
- tdata->resp->body->content);
- }
- // Free the threaddata
- freeThreadData(tdata);
- }
- freeFileInternal(file);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsFileIsOpenForRead(hdfsFile file)
-{
- return (file->type == INPUT);
-}
-
-int hdfsFileGetReadStatistics(hdfsFile file,
- struct hdfsReadStatistics **stats)
-{
- errno = ENOTSUP;
- return -1;
-}
-
-int64_t hdfsReadStatisticsGetRemoteBytesRead(
- const struct hdfsReadStatistics *stats)
-{
- return stats->totalBytesRead - stats->totalLocalBytesRead;
-}
-
-void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats)
-{
- free(stats);
-}
-
-int hdfsFileIsOpenForWrite(hdfsFile file)
-{
- return (file->type == OUTPUT);
-}
-
-static int hdfsReadImpl(hdfsFS fs, hdfsFile file, void* buffer, tSize off,
- tSize length, tSize *numRead)
-{
- int ret = 0;
- char *url = NULL;
- struct Response *resp = NULL;
-
- if (fs == NULL || file == NULL || file->type != INPUT || buffer == NULL ||
- length < 0) {
- ret = EINVAL;
- goto done;
- }
- if (length == 0) {
- // Special case: the user supplied a buffer of zero length, so there is
- // nothing to do.
- *numRead = 0;
- goto done;
- }
- resp = calloc(1, sizeof(*resp)); // resp is actually a pointer type
- if (!resp) {
- ret = ENOMEM;
- goto done;
- }
- ret = initResponseBuffer(&(resp->header));
- if (ret) {
- goto done;
- }
- ret = initResponseBuffer(&(resp->body));
- if (ret) {
- goto done;
- }
- memset(buffer, 0, length);
- resp->body->content = buffer;
- resp->body->remaining = length;
-
- ret = createUrlForOPEN(fs->nn, fs->port, file->file->absPath,
- fs->userName, off, length, &url);
- if (ret) {
- goto done;
- }
- ret = launchOPEN(url, resp);
- if (ret) {
- goto done;
- }
- ret = parseOPEN(resp->header->content, resp->body->content);
- if (ret == -1) {
- // Special case: if parseOPEN returns -1, we asked for a byte range
- // with outside what the file contains. In this case, hdfsRead and
- // hdfsPread return 0, meaning end-of-file.
- *numRead = 0;
- } else if (ret == 0) {
- *numRead = (tSize) resp->body->offset;
- }
-done:
- if (resp) {
- freeResponseBuffer(resp->header);
- free(resp->body);
- }
- free(resp);
- free(url);
- return ret;
-}
-
-tSize hdfsRead(hdfsFS fs, hdfsFile file, void* buffer, tSize length)
-{
- int ret = 0;
- tSize numRead = 0;
-
- ret = hdfsReadImpl(fs, file, buffer, (tSize) file->offset,
- length, &numRead);
- if (ret > 0) { // ret == -1 means end of file
- errno = ret;
- return -1;
- }
- file->offset += numRead;
- return numRead;
-}
-
-int hdfsAvailable(hdfsFS fs, hdfsFile file)
-{
- /* We actually always block when reading from webhdfs, currently. So the
- * number of bytes that can be read without blocking is currently 0.
- */
- return 0;
-}
-
-int hdfsSeek(hdfsFS fs, hdfsFile file, tOffset desiredPos)
-{
- struct webhdfsFileHandle *wf;
- hdfsFileInfo *fileInfo = NULL;
- int ret = 0;
-
- if (!fs || !file || (file->type == OUTPUT) || (desiredPos < 0)) {
- ret = EINVAL;
- goto done;
- }
- wf = file->file;
- if (!wf) {
- ret = EINVAL;
- goto done;
- }
- fileInfo = hdfsGetPathInfo(fs, wf->absPath);
- if (!fileInfo) {
- ret = errno;
- goto done;
- }
- if (desiredPos > fileInfo->mSize) {
- fprintf(stderr,
- "hdfsSeek for %s failed since the desired position %" PRId64
- " is beyond the size of the file %" PRId64 "\n",
- wf->absPath, desiredPos, fileInfo->mSize);
- ret = ENOTSUP;
- goto done;
- }
- file->offset = desiredPos;
-
-done:
- if (fileInfo) {
- hdfsFreeFileInfo(fileInfo, 1);
- }
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-tSize hdfsPread(hdfsFS fs, hdfsFile file, tOffset position,
- void* buffer, tSize length)
-{
- int ret;
- tSize numRead = 0;
-
- if (position < 0) {
- errno = EINVAL;
- return -1;
- }
- ret = hdfsReadImpl(fs, file, buffer, (tSize) position, length, &numRead);
- if (ret > 0) {
- errno = ret;
- return -1;
- }
- return numRead;
-}
-
-tOffset hdfsTell(hdfsFS fs, hdfsFile file)
-{
- if (!file) {
- errno = EINVAL;
- return -1;
- }
- return file->offset;
-}
-
-char* hdfsGetWorkingDirectory(hdfsFS fs, char *buffer, size_t bufferSize)
-{
- int strlength;
- if (fs == NULL || buffer == NULL || bufferSize <= 0) {
- errno = EINVAL;
- return NULL;
- }
- strlength = snprintf(buffer, bufferSize, "%s", fs->workingDir);
- if (strlength >= bufferSize) {
- errno = ENAMETOOLONG;
- return NULL;
- } else if (strlength < 0) {
- errno = EIO;
- return NULL;
- }
- return buffer;
-}
-
-/** Replace "//" with "/" in path */
-static void normalizePath(char *path)
-{
- int i = 0, j = 0, sawslash = 0;
-
- for (i = j = sawslash = 0; path[i] != '\0'; i++) {
- if (path[i] != '/') {
- sawslash = 0;
- path[j++] = path[i];
- } else if (path[i] == '/' && !sawslash) {
- sawslash = 1;
- path[j++] = '/';
- }
- }
- path[j] = '\0';
-}
-
-int hdfsSetWorkingDirectory(hdfsFS fs, const char* path)
-{
- char *newWorkingDir = NULL;
- size_t strlenPath = 0, newWorkingDirLen = 0;
- int strlength;
-
- if (fs == NULL || path == NULL) {
- errno = EINVAL;
- return -1;
- }
- strlenPath = strlen(path);
- if (strlenPath < 1) {
- errno = EINVAL;
- return -1;
- }
- // the max string length of the new working dir is
- // (length of old working dir) + (length of given path) + strlen("/") + 1
- newWorkingDirLen = strlen(fs->workingDir) + strlenPath + 2;
- newWorkingDir = malloc(newWorkingDirLen);
- if (!newWorkingDir) {
- errno = ENOMEM;
- return -1;
- }
- strlength = snprintf(newWorkingDir, newWorkingDirLen, "%s%s%s",
- (path[0] == '/') ? "" : fs->workingDir,
- path, (path[strlenPath - 1] == '/') ? "" : "/");
- if (strlength < 0 || strlength >= newWorkingDirLen) {
- free(newWorkingDir);
- errno = EIO;
- return -1;
- }
-
- if (strstr(path, "//")) {
- // normalize the path by replacing "//" with "/"
- normalizePath(newWorkingDir);
- }
-
- free(fs->workingDir);
- fs->workingDir = newWorkingDir;
- return 0;
-}
-
-void hdfsFreeHosts(char ***blockHosts)
-{
- int i, j;
- for (i=0; blockHosts[i]; i++) {
- for (j=0; blockHosts[i][j]; j++) {
- free(blockHosts[i][j]);
- }
- free(blockHosts[i]);
- }
- free(blockHosts);
-}
-
-tOffset hdfsGetDefaultBlockSize(hdfsFS fs)
-{
- errno = ENOTSUP;
- return -1;
-}
-
-int hdfsFileUsesDirectRead(hdfsFile file)
-{
- return 0; // webhdfs never performs direct reads.
-}
-
-void hdfsFileDisableDirectRead(hdfsFile file)
-{
- // webhdfs never performs direct reads
-}
-
-int hdfsHFlush(hdfsFS fs, hdfsFile file)
-{
- if (file->type != OUTPUT) {
- errno = EINVAL;
- return -1;
- }
- // TODO: block until our write buffer is flushed (HDFS-3952)
- return 0;
-}
-
-int hdfsFlush(hdfsFS fs, hdfsFile file)
-{
- if (file->type != OUTPUT) {
- errno = EINVAL;
- return -1;
- }
- // TODO: block until our write buffer is flushed (HDFS-3952)
- return 0;
-}
-
-char*** hdfsGetHosts(hdfsFS fs, const char* path,
- tOffset start, tOffset length)
-{
- errno = ENOTSUP;
- return NULL;
-}
-
-tOffset hdfsGetCapacity(hdfsFS fs)
-{
- errno = ENOTSUP;
- return -1;
-}
-
-tOffset hdfsGetUsed(hdfsFS fs)
-{
- errno = ENOTSUP;
- return -1;
-}
-
-int hdfsCopy(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst)
-{
- errno = ENOTSUP;
- return -1;
-}
-
-int hdfsMove(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst)
-{
- errno = ENOTSUP;
- return -1;
-}
-
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_ops.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_ops.c b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_ops.c
deleted file mode 100644
index 87550ae..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_ops.c
+++ /dev/null
@@ -1,552 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "hdfs.h"
-#include "native_mini_dfs.h"
-
-#include <inttypes.h>
-#include <jni.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <unistd.h>
-
-static struct NativeMiniDfsCluster *cluster;
-
-void permission_disp(short permissions, char *rtr)
-{
- rtr[9] = '\0';
- int i;
- short perm;
- for(i = 2; i >= 0; i--)
- {
- perm = permissions >> (i * 3);
- rtr[0] = perm & 4 ? 'r' : '-';
- rtr[1] = perm & 2 ? 'w' : '-';
- rtr[2] = perm & 1 ? 'x' : '-';
- rtr += 3;
- }
-}
-
-int main(int argc, char **argv)
-{
- char buffer[32];
- tSize num_written_bytes;
- const char* slashTmp = "/tmp";
- int nnPort;
- char *rwTemplate, *rwTemplate2, *newDirTemplate,
- *appendTemplate, *userTemplate, *rwPath = NULL;
- const char* fileContents = "Hello, World!";
- const char* nnHost = NULL;
-
- if (argc != 2) {
- fprintf(stderr, "usage: test_libwebhdfs_ops <username>\n");
- exit(1);
- }
-
- struct NativeMiniDfsConf conf = {
- .doFormat = 1, .webhdfsEnabled = 1, .namenodeHttpPort = 50070,
- };
- cluster = nmdCreate(&conf);
- if (!cluster) {
- fprintf(stderr, "Failed to create the NativeMiniDfsCluster.\n");
- exit(1);
- }
- if (nmdWaitClusterUp(cluster)) {
- fprintf(stderr, "Error when waiting for cluster to be ready.\n");
- exit(1);
- }
- if (nmdGetNameNodeHttpAddress(cluster, &nnPort, &nnHost)) {
- fprintf(stderr, "Error when retrieving namenode host address.\n");
- exit(1);
- }
-
- hdfsFS fs = hdfsConnectAsUserNewInstance(nnHost, nnPort, argv[1]);
- if(!fs) {
- fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
- exit(-1);
- }
-
- {
- // Write tests
- rwTemplate = strdup("/tmp/helloWorldXXXXXX");
- if (!rwTemplate) {
- fprintf(stderr, "Failed to create rwTemplate!\n");
- exit(1);
- }
- rwPath = mktemp(rwTemplate);
- // hdfsOpenFile
- hdfsFile writeFile = hdfsOpenFile(fs, rwPath,
- O_WRONLY|O_CREAT, 0, 0, 0);
-
- if(!writeFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", rwPath);
- exit(1);
- }
- fprintf(stderr, "Opened %s for writing successfully...\n", rwPath);
- // hdfsWrite
- num_written_bytes = hdfsWrite(fs, writeFile, (void*)fileContents,
- (int) strlen(fileContents) + 1);
- if (num_written_bytes != strlen(fileContents) + 1) {
- fprintf(stderr, "Failed to write correct number of bytes - "
- "expected %d, got %d\n",
- (int)(strlen(fileContents) + 1), (int) num_written_bytes);
- exit(1);
- }
- fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
-
- // hdfsTell
- tOffset currentPos = -1;
- if ((currentPos = hdfsTell(fs, writeFile)) == -1) {
- fprintf(stderr,
- "Failed to get current file position correctly. Got %"
- PRId64 "!\n", currentPos);
- exit(1);
- }
- fprintf(stderr, "Current position: %" PRId64 "\n", currentPos);
-
- hdfsCloseFile(fs, writeFile);
- // Done test write
- }
-
- sleep(1);
-
- {
- //Read tests
- int available = 0, exists = 0;
-
- // hdfsExists
- exists = hdfsExists(fs, rwPath);
- if (exists) {
- fprintf(stderr, "Failed to validate existence of %s\n", rwPath);
- exists = hdfsExists(fs, rwPath);
- if (exists) {
- fprintf(stderr,
- "Still failed to validate existence of %s\n", rwPath);
- exit(1);
- }
- }
-
- hdfsFile readFile = hdfsOpenFile(fs, rwPath, O_RDONLY, 0, 0, 0);
- if (!readFile) {
- fprintf(stderr, "Failed to open %s for reading!\n", rwPath);
- exit(1);
- }
- if (!hdfsFileIsOpenForRead(readFile)) {
- fprintf(stderr, "hdfsFileIsOpenForRead: we just opened a file "
- "with O_RDONLY, and it did not show up as 'open for "
- "read'\n");
- exit(1);
- }
-
- available = hdfsAvailable(fs, readFile);
- fprintf(stderr, "hdfsAvailable: %d\n", available);
-
- // hdfsSeek, hdfsTell
- tOffset seekPos = 1;
- if(hdfsSeek(fs, readFile, seekPos)) {
- fprintf(stderr, "Failed to seek %s for reading!\n", rwPath);
- exit(1);
- }
-
- tOffset currentPos = -1;
- if((currentPos = hdfsTell(fs, readFile)) != seekPos) {
- fprintf(stderr,
- "Failed to get current file position correctly! Got %"
- PRId64 "!\n", currentPos);
-
- exit(1);
- }
- fprintf(stderr, "Current position: %" PRId64 "\n", currentPos);
-
- if(hdfsSeek(fs, readFile, 0)) {
- fprintf(stderr, "Failed to seek %s for reading!\n", rwPath);
- exit(1);
- }
-
- // hdfsRead
- memset(buffer, 0, sizeof(buffer));
- tSize num_read_bytes = hdfsRead(fs, readFile, buffer, sizeof(buffer));
- if (strncmp(fileContents, buffer, strlen(fileContents)) != 0) {
- fprintf(stderr, "Failed to read (direct). "
- "Expected %s but got %s (%d bytes)\n",
- fileContents, buffer, num_read_bytes);
- exit(1);
- }
- fprintf(stderr, "Read following %d bytes:\n%s\n",
- num_read_bytes, buffer);
-
- if (hdfsSeek(fs, readFile, 0L)) {
- fprintf(stderr, "Failed to seek to file start!\n");
- exit(1);
- }
-
- // hdfsPread
- memset(buffer, 0, strlen(fileContents + 1));
- num_read_bytes = hdfsPread(fs, readFile, 0, buffer, sizeof(buffer));
- fprintf(stderr, "Read following %d bytes:\n%s\n",
- num_read_bytes, buffer);
-
- hdfsCloseFile(fs, readFile);
- // Done test read
- }
-
- int totalResult = 0;
- int result = 0;
- {
- //Generic file-system operations
- char *srcPath = rwPath;
- char buffer[256];
- const char *resp;
- rwTemplate2 = strdup("/tmp/helloWorld2XXXXXX");
- if (!rwTemplate2) {
- fprintf(stderr, "Failed to create rwTemplate2!\n");
- exit(1);
- }
- char *dstPath = mktemp(rwTemplate2);
- newDirTemplate = strdup("/tmp/newdirXXXXXX");
- if (!newDirTemplate) {
- fprintf(stderr, "Failed to create newDirTemplate!\n");
- exit(1);
- }
- char *newDirectory = mktemp(newDirTemplate);
-
- // hdfsRename
- fprintf(stderr, "hdfsRename: %s\n",
- ((result = hdfsRename(fs, rwPath, dstPath)) ?
- "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsRename back: %s\n",
- ((result = hdfsRename(fs, dstPath, srcPath)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- // hdfsCreateDirectory
- fprintf(stderr, "hdfsCreateDirectory: %s\n",
- ((result = hdfsCreateDirectory(fs, newDirectory)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- // hdfsSetReplication
- fprintf(stderr, "hdfsSetReplication: %s\n",
- ((result = hdfsSetReplication(fs, srcPath, 1)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- // hdfsGetWorkingDirectory, hdfsSetWorkingDirectory
- fprintf(stderr, "hdfsGetWorkingDirectory: %s\n",
- ((resp = hdfsGetWorkingDirectory(fs, buffer, sizeof(buffer))) ?
- buffer : "Failed!"));
- totalResult += (resp ? 0 : 1);
-
- const char* path[] = {"/foo", "/foo/bar", "foobar", "//foo/bar//foobar",
- "foo//bar", "foo/bar///", "/", "////"};
- int i;
- for (i = 0; i < 8; i++) {
- fprintf(stderr, "hdfsSetWorkingDirectory: %s, %s\n",
- ((result = hdfsSetWorkingDirectory(fs, path[i])) ?
- "Failed!" : "Success!"),
- hdfsGetWorkingDirectory(fs, buffer, sizeof(buffer)));
- totalResult += result;
- }
-
- fprintf(stderr, "hdfsSetWorkingDirectory: %s\n",
- ((result = hdfsSetWorkingDirectory(fs, slashTmp)) ?
- "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsGetWorkingDirectory: %s\n",
- ((resp = hdfsGetWorkingDirectory(fs, buffer, sizeof(buffer))) ?
- buffer : "Failed!"));
- totalResult += (resp ? 0 : 1);
-
- // hdfsGetPathInfo
- hdfsFileInfo *fileInfo = NULL;
- if((fileInfo = hdfsGetPathInfo(fs, slashTmp)) != NULL) {
- fprintf(stderr, "hdfsGetPathInfo - SUCCESS!\n");
- fprintf(stderr, "Name: %s, ", fileInfo->mName);
- fprintf(stderr, "Type: %c, ", (char)(fileInfo->mKind));
- fprintf(stderr, "Replication: %d, ", fileInfo->mReplication);
- fprintf(stderr, "BlockSize: %"PRId64", ", fileInfo->mBlockSize);
- fprintf(stderr, "Size: %"PRId64", ", fileInfo->mSize);
- fprintf(stderr, "LastMod: %s", ctime(&fileInfo->mLastMod));
- fprintf(stderr, "Owner: %s, ", fileInfo->mOwner);
- fprintf(stderr, "Group: %s, ", fileInfo->mGroup);
- char permissions[10];
- permission_disp(fileInfo->mPermissions, permissions);
- fprintf(stderr, "Permissions: %d (%s)\n",
- fileInfo->mPermissions, permissions);
- hdfsFreeFileInfo(fileInfo, 1);
- } else {
- totalResult++;
- fprintf(stderr, "hdfsGetPathInfo for %s - FAILED!\n", slashTmp);
- }
-
- // hdfsListDirectory
- hdfsFileInfo *fileList = 0;
- int numEntries = 0;
- if((fileList = hdfsListDirectory(fs, slashTmp, &numEntries)) != NULL) {
- int i = 0;
- for(i=0; i < numEntries; ++i) {
- fprintf(stderr, "Name: %s, ", fileList[i].mName);
- fprintf(stderr, "Type: %c, ", (char)fileList[i].mKind);
- fprintf(stderr, "Replication: %d, ", fileList[i].mReplication);
- fprintf(stderr, "BlockSize: %"PRId64", ", fileList[i].mBlockSize);
- fprintf(stderr, "Size: %"PRId64", ", fileList[i].mSize);
- fprintf(stderr, "LastMod: %s", ctime(&fileList[i].mLastMod));
- fprintf(stderr, "Owner: %s, ", fileList[i].mOwner);
- fprintf(stderr, "Group: %s, ", fileList[i].mGroup);
- char permissions[10];
- permission_disp(fileList[i].mPermissions, permissions);
- fprintf(stderr, "Permissions: %d (%s)\n",
- fileList[i].mPermissions, permissions);
- }
- hdfsFreeFileInfo(fileList, numEntries);
- } else {
- if (errno) {
- totalResult++;
- fprintf(stderr, "waah! hdfsListDirectory - FAILED!\n");
- } else {
- fprintf(stderr, "Empty directory!\n");
- }
- }
-
- char *newOwner = "root";
- // Setting tmp dir to 777 so later when connectAsUser nobody,
- // we can write to it
- short newPerm = 0666;
-
- // hdfsChown
- fprintf(stderr, "hdfsChown: %s\n",
- ((result = hdfsChown(fs, rwPath, NULL, "users")) ?
- "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsChown: %s\n",
- ((result = hdfsChown(fs, rwPath, newOwner, NULL)) ?
- "Failed!" : "Success!"));
- totalResult += result;
- // hdfsChmod
- fprintf(stderr, "hdfsChmod: %s\n",
- ((result = hdfsChmod(fs, rwPath, newPerm)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- sleep(2);
- tTime newMtime = time(NULL);
- tTime newAtime = time(NULL);
-
- // utime write
- fprintf(stderr, "hdfsUtime: %s\n",
- ((result = hdfsUtime(fs, rwPath, newMtime, newAtime)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- // chown/chmod/utime read
- hdfsFileInfo *finfo = hdfsGetPathInfo(fs, rwPath);
-
- fprintf(stderr, "hdfsChown read: %s\n",
- ((result = (strcmp(finfo->mOwner, newOwner) != 0)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- fprintf(stderr, "hdfsChmod read: %s\n",
- ((result = (finfo->mPermissions != newPerm)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- // will later use /tmp/ as a different user so enable it
- fprintf(stderr, "hdfsChmod: %s\n",
- ((result = hdfsChmod(fs, slashTmp, 0777)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- fprintf(stderr,"newMTime=%ld\n",newMtime);
- fprintf(stderr,"curMTime=%ld\n",finfo->mLastMod);
-
-
- fprintf(stderr, "hdfsUtime read (mtime): %s\n",
- ((result = (finfo->mLastMod != newMtime / 1000)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- // Clean up
- hdfsFreeFileInfo(finfo, 1);
- fprintf(stderr, "hdfsDelete: %s\n",
- ((result = hdfsDelete(fs, newDirectory, 1)) ?
- "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsDelete: %s\n",
- ((result = hdfsDelete(fs, srcPath, 1)) ?
- "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsExists: %s\n",
- ((result = hdfsExists(fs, newDirectory)) ?
- "Success!" : "Failed!"));
- totalResult += (result ? 0 : 1);
- // Done test generic operations
- }
-
- {
- // Test Appends
- appendTemplate = strdup("/tmp/appendsXXXXXX");
- if (!appendTemplate) {
- fprintf(stderr, "Failed to create appendTemplate!\n");
- exit(1);
- }
- char *appendPath = mktemp(appendTemplate);
- const char* helloBuffer = "Hello,";
- hdfsFile writeFile = NULL;
-
- // Create
- writeFile = hdfsOpenFile(fs, appendPath, O_WRONLY, 0, 0, 0);
- if(!writeFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", appendPath);
- exit(1);
- }
- fprintf(stderr, "Opened %s for writing successfully...\n", appendPath);
-
- num_written_bytes = hdfsWrite(fs, writeFile, helloBuffer,
- (int) strlen(helloBuffer));
- fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
- hdfsCloseFile(fs, writeFile);
-
- fprintf(stderr, "hdfsSetReplication: %s\n",
- ((result = hdfsSetReplication(fs, appendPath, 1)) ?
- "Failed!" : "Success!"));
- totalResult += result;
-
- // Re-Open for Append
- writeFile = hdfsOpenFile(fs, appendPath, O_WRONLY | O_APPEND, 0, 0, 0);
- if(!writeFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", appendPath);
- exit(1);
- }
- fprintf(stderr, "Opened %s for appending successfully...\n",
- appendPath);
-
- helloBuffer = " World";
- num_written_bytes = hdfsWrite(fs, writeFile, helloBuffer,
- (int)strlen(helloBuffer) + 1);
- fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
-
- hdfsCloseFile(fs, writeFile);
-
- // Check size
- hdfsFileInfo *finfo = hdfsGetPathInfo(fs, appendPath);
- fprintf(stderr, "fileinfo->mSize: == total %s\n",
- ((result = (finfo->mSize == strlen("Hello, World") + 1)) ?
- "Success!" : "Failed!"));
- totalResult += (result ? 0 : 1);
-
- // Read and check data
- hdfsFile readFile = hdfsOpenFile(fs, appendPath, O_RDONLY, 0, 0, 0);
- if (!readFile) {
- fprintf(stderr, "Failed to open %s for reading!\n", appendPath);
- exit(1);
- }
-
- tSize num_read_bytes = hdfsRead(fs, readFile, buffer, sizeof(buffer));
- fprintf(stderr, "Read following %d bytes:\n%s\n",
- num_read_bytes, buffer);
- fprintf(stderr, "read == Hello, World %s\n",
- (result = (strcmp(buffer, "Hello, World") == 0)) ?
- "Success!" : "Failed!");
- hdfsCloseFile(fs, readFile);
-
- // Cleanup
- fprintf(stderr, "hdfsDelete: %s\n",
- ((result = hdfsDelete(fs, appendPath, 1)) ?
- "Failed!" : "Success!"));
- totalResult += result;
- // Done test appends
- }
-
- totalResult += (hdfsDisconnect(fs) != 0);
-
- {
- //
- // Now test as connecting as a specific user
- // This only meant to test that we connected as that user, not to test
- // the actual fs user capabilities. Thus just create a file and read
- // the owner is correct.
- const char *tuser = "nobody";
- userTemplate = strdup("/tmp/usertestXXXXXX");
- if (!userTemplate) {
- fprintf(stderr, "Failed to create userTemplate!\n");
- exit(1);
- }
- char* userWritePath = mktemp(userTemplate);
- hdfsFile writeFile = NULL;
-
- fs = hdfsConnectAsUserNewInstance("default", 50070, tuser);
- if(!fs) {
- fprintf(stderr,
- "Oops! Failed to connect to hdfs as user %s!\n",tuser);
- exit(1);
- }
-
- writeFile = hdfsOpenFile(fs, userWritePath, O_WRONLY|O_CREAT, 0, 0, 0);
- if(!writeFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", userWritePath);
- exit(1);
- }
- fprintf(stderr, "Opened %s for writing successfully...\n",
- userWritePath);
-
- num_written_bytes = hdfsWrite(fs, writeFile, fileContents,
- (int)strlen(fileContents) + 1);
- fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
- hdfsCloseFile(fs, writeFile);
-
- hdfsFileInfo *finfo = hdfsGetPathInfo(fs, userWritePath);
- if (finfo) {
- fprintf(stderr, "hdfs new file user is correct: %s\n",
- ((result = (strcmp(finfo->mOwner, tuser) != 0)) ?
- "Failed!" : "Success!"));
- } else {
- fprintf(stderr,
- "hdfsFileInfo returned by hdfsGetPathInfo is NULL\n");
- result = -1;
- }
- totalResult += result;
-
- // Cleanup
- fprintf(stderr, "hdfsDelete: %s\n",
- ((result = hdfsDelete(fs, userWritePath, 1)) ?
- "Failed!" : "Success!"));
- totalResult += result;
- // Done test specific user
- }
-
- totalResult += (hdfsDisconnect(fs) != 0);
-
- // Shutdown the native minidfscluster
- nmdShutdown(cluster);
- nmdFree(cluster);
-
- fprintf(stderr, "totalResult == %d\n", totalResult);
- if (totalResult != 0) {
- return -1;
- } else {
- return 0;
- }
-}
-
-/**
- * vim: ts=4: sw=4: et:
- */
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_read.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_read.c b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_read.c
deleted file mode 100644
index 4bd3078..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_read.c
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "hdfs.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-int main(int argc, char **argv) {
-
- const char* rfile;
- tSize fileTotalSize, bufferSize, curSize, totalReadSize;
- hdfsFS fs;
- hdfsFile readFile;
- char *buffer = NULL;
-
- if (argc != 4) {
- fprintf(stderr, "Usage: test_libwebhdfs_read"
- " <filename> <filesize> <buffersize>\n");
- exit(1);
- }
-
- fs = hdfsConnect("localhost", 50070);
- if (!fs) {
- fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
- exit(1);
- }
-
- rfile = argv[1];
- fileTotalSize = strtoul(argv[2], NULL, 10);
- bufferSize = strtoul(argv[3], NULL, 10);
-
- readFile = hdfsOpenFile(fs, rfile, O_RDONLY, bufferSize, 0, 0);
- if (!readFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", rfile);
- exit(1);
- }
-
- // data to be written to the file
- buffer = malloc(sizeof(char) * bufferSize);
- if(buffer == NULL) {
- fprintf(stderr, "Failed to allocate buffer.\n");
- exit(1);
- }
-
- // read from the file
- curSize = bufferSize;
- totalReadSize = 0;
- for (; (curSize = hdfsRead(fs, readFile, buffer, bufferSize)) == bufferSize; ) {
- totalReadSize += curSize;
- }
- totalReadSize += curSize;
-
- fprintf(stderr, "size of the file: %d; reading size: %d\n",
- fileTotalSize, totalReadSize);
-
- free(buffer);
- hdfsCloseFile(fs, readFile);
- hdfsDisconnect(fs);
-
- return 0;
-}
-
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_threaded.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_threaded.c b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_threaded.c
deleted file mode 100644
index 6c9a12e..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_threaded.c
+++ /dev/null
@@ -1,247 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "expect.h"
-#include "hdfs.h"
-#include "native_mini_dfs.h"
-
-#include <errno.h>
-#include <semaphore.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define TLH_MAX_THREADS 100
-
-static struct NativeMiniDfsCluster* cluster;
-
-static const char *user;
-
-struct tlhThreadInfo {
- /** Thread index */
- int threadIdx;
- /** 0 = thread was successful; error code otherwise */
- int success;
- /** pthread identifier */
- pthread_t thread;
-};
-
-static int hdfsSingleNameNodeConnect(struct NativeMiniDfsCluster *cluster,
- hdfsFS *fs)
-{
- int nnPort;
- const char *nnHost;
- hdfsFS hdfs;
-
- if (nmdGetNameNodeHttpAddress(cluster, &nnPort, &nnHost)) {
- fprintf(stderr, "Error when retrieving namenode host address.\n");
- return 1;
- }
-
- hdfs = hdfsConnectAsUser(nnHost, nnPort, user);
- if(!hdfs) {
- fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
- return 1;
- }
-
- *fs = hdfs;
- return 0;
-}
-
-static int doTestHdfsOperations(struct tlhThreadInfo *ti, hdfsFS fs)
-{
- char prefix[256], tmp[256];
- hdfsFile file;
- int ret, expected;
- hdfsFileInfo *fileInfo;
-
- snprintf(prefix, sizeof(prefix), "/tlhData%04d", ti->threadIdx);
-
- if (hdfsExists(fs, prefix) == 0) {
- EXPECT_ZERO(hdfsDelete(fs, prefix, 1));
- }
- EXPECT_ZERO(hdfsCreateDirectory(fs, prefix));
- snprintf(tmp, sizeof(tmp), "%s/file", prefix);
-
- EXPECT_NONNULL(hdfsOpenFile(fs, tmp, O_RDONLY, 0, 0, 0));
-
- file = hdfsOpenFile(fs, tmp, O_WRONLY, 0, 0, 0);
- EXPECT_NONNULL(file);
-
- /* TODO: implement writeFully and use it here */
- expected = (int)strlen(prefix);
- ret = hdfsWrite(fs, file, prefix, expected);
- if (ret < 0) {
- ret = errno;
- fprintf(stderr, "hdfsWrite failed and set errno %d\n", ret);
- return ret;
- }
- if (ret != expected) {
- fprintf(stderr, "hdfsWrite was supposed to write %d bytes, but "
- "it wrote %d\n", ret, expected);
- return EIO;
- }
- EXPECT_ZERO(hdfsFlush(fs, file));
- EXPECT_ZERO(hdfsCloseFile(fs, file));
-
- /* Let's re-open the file for reading */
- file = hdfsOpenFile(fs, tmp, O_RDONLY, 0, 0, 0);
- EXPECT_NONNULL(file);
-
- /* TODO: implement readFully and use it here */
- ret = hdfsRead(fs, file, tmp, sizeof(tmp));
- if (ret < 0) {
- ret = errno;
- fprintf(stderr, "hdfsRead failed and set errno %d\n", ret);
- return ret;
- }
- if (ret != expected) {
- fprintf(stderr, "hdfsRead was supposed to read %d bytes, but "
- "it read %d\n", ret, expected);
- return EIO;
- }
- EXPECT_ZERO(memcmp(prefix, tmp, expected));
- EXPECT_ZERO(hdfsCloseFile(fs, file));
-
- snprintf(tmp, sizeof(tmp), "%s/file", prefix);
- EXPECT_NONZERO(hdfsChown(fs, tmp, NULL, NULL));
- EXPECT_ZERO(hdfsChown(fs, tmp, NULL, "doop"));
- fileInfo = hdfsGetPathInfo(fs, tmp);
- EXPECT_NONNULL(fileInfo);
- EXPECT_ZERO(strcmp("doop", fileInfo->mGroup));
- hdfsFreeFileInfo(fileInfo, 1);
-
- EXPECT_ZERO(hdfsChown(fs, tmp, "ha", "doop2"));
- fileInfo = hdfsGetPathInfo(fs, tmp);
- EXPECT_NONNULL(fileInfo);
- EXPECT_ZERO(strcmp("ha", fileInfo->mOwner));
- EXPECT_ZERO(strcmp("doop2", fileInfo->mGroup));
- hdfsFreeFileInfo(fileInfo, 1);
-
- EXPECT_ZERO(hdfsChown(fs, tmp, "ha2", NULL));
- fileInfo = hdfsGetPathInfo(fs, tmp);
- EXPECT_NONNULL(fileInfo);
- EXPECT_ZERO(strcmp("ha2", fileInfo->mOwner));
- EXPECT_ZERO(strcmp("doop2", fileInfo->mGroup));
- hdfsFreeFileInfo(fileInfo, 1);
-
- EXPECT_ZERO(hdfsDelete(fs, prefix, 1));
- return 0;
-}
-
-static void *testHdfsOperations(void *v)
-{
- struct tlhThreadInfo *ti = (struct tlhThreadInfo*)v;
- hdfsFS fs = NULL;
- int ret;
-
- fprintf(stderr, "testHdfsOperations(threadIdx=%d): starting\n",
- ti->threadIdx);
- ret = hdfsSingleNameNodeConnect(cluster, &fs);
- if (ret) {
- fprintf(stderr, "testHdfsOperations(threadIdx=%d): "
- "hdfsSingleNameNodeConnect failed with error %d.\n",
- ti->threadIdx, ret);
- ti->success = EIO;
- return NULL;
- }
- ti->success = doTestHdfsOperations(ti, fs);
- if (hdfsDisconnect(fs)) {
- ret = errno;
- fprintf(stderr, "hdfsDisconnect error %d\n", ret);
- ti->success = ret;
- }
- return NULL;
-}
-
-static int checkFailures(struct tlhThreadInfo *ti, int tlhNumThreads)
-{
- int i, threadsFailed = 0;
- const char *sep = "";
-
- for (i = 0; i < tlhNumThreads; i++) {
- if (ti[i].success != 0) {
- threadsFailed = 1;
- }
- }
- if (!threadsFailed) {
- fprintf(stderr, "testLibHdfs: all threads succeeded. SUCCESS.\n");
- return EXIT_SUCCESS;
- }
- fprintf(stderr, "testLibHdfs: some threads failed: [");
- for (i = 0; i < tlhNumThreads; i++) {
- if (ti[i].success != 0) {
- fprintf(stderr, "%s%d", sep, i);
- sep = ", ";
- }
- }
- fprintf(stderr, "]. FAILURE.\n");
- return EXIT_FAILURE;
-}
-
-/**
- * Test that we can write a file with libhdfs and then read it back
- */
-int main(int argc, const char *args[])
-{
- int i, tlhNumThreads;
- const char *tlhNumThreadsStr;
- struct tlhThreadInfo ti[TLH_MAX_THREADS];
-
- if (argc != 2) {
- fprintf(stderr, "usage: test_libwebhdfs_threaded <username>\n");
- exit(1);
- }
- user = args[1];
-
- struct NativeMiniDfsConf conf = {
- .doFormat = 1, .webhdfsEnabled = 1, .namenodeHttpPort = 50070,
- };
- cluster = nmdCreate(&conf);
- EXPECT_NONNULL(cluster);
- EXPECT_ZERO(nmdWaitClusterUp(cluster));
-
- tlhNumThreadsStr = getenv("TLH_NUM_THREADS");
- if (!tlhNumThreadsStr) {
- tlhNumThreadsStr = "3";
- }
- tlhNumThreads = atoi(tlhNumThreadsStr);
- if ((tlhNumThreads <= 0) || (tlhNumThreads > TLH_MAX_THREADS)) {
- fprintf(stderr, "testLibHdfs: must have a number of threads "
- "between 1 and %d inclusive, not %d\n",
- TLH_MAX_THREADS, tlhNumThreads);
- return EXIT_FAILURE;
- }
- memset(&ti[0], 0, sizeof(ti));
- for (i = 0; i < tlhNumThreads; i++) {
- ti[i].threadIdx = i;
- }
-
- for (i = 0; i < tlhNumThreads; i++) {
- EXPECT_ZERO(pthread_create(&ti[i].thread, NULL,
- testHdfsOperations, &ti[i]));
- }
- for (i = 0; i < tlhNumThreads; i++) {
- EXPECT_ZERO(pthread_join(ti[i].thread, NULL));
- }
-
- EXPECT_ZERO(nmdShutdown(cluster));
- nmdFree(cluster);
- return checkFailures(ti, tlhNumThreads);
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_write.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_write.c b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_write.c
deleted file mode 100644
index 652fb86..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/test_libwebhdfs_write.c
+++ /dev/null
@@ -1,111 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "hdfs.h"
-
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <inttypes.h>
-
-int main(int argc, char **argv) {
- hdfsFS fs;
- const char* writeFileName;
- off_t fileTotalSize;
- long long tmpBufferSize;
- tSize bufferSize = 0, totalWriteSize = 0, toWrite = 0, written = 0;
- hdfsFile writeFile = NULL;
- int append, i = 0;
- char* buffer = NULL;
-
- if (argc != 6) {
- fprintf(stderr, "Usage: test_libwebhdfs_write <filename> <filesize> "
- "<buffersize> <username> <append>\n");
- exit(1);
- }
-
- fs = hdfsConnectAsUser("default", 50070, argv[4]);
- if (!fs) {
- fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
- exit(1);
- }
-
- writeFileName = argv[1];
- fileTotalSize = strtoul(argv[2], NULL, 10);
- tmpBufferSize = strtoul(argv[3], NULL, 10);
-
- // sanity check
- if(fileTotalSize == ULONG_MAX && errno == ERANGE) {
- fprintf(stderr, "invalid file size %s - must be <= %lu\n",
- argv[2], ULONG_MAX);
- exit(1);
- }
-
- // currently libhdfs writes are of tSize which is int32
- if(tmpBufferSize > INT_MAX) {
- fprintf(stderr,
- "invalid buffer size libhdfs API write chunks must be <= %d\n",
- INT_MAX);
- exit(1);
- }
-
- bufferSize = (tSize) tmpBufferSize;
- append = atoi(argv[5]);
- if (!append) {
- writeFile = hdfsOpenFile(fs, writeFileName, O_WRONLY, bufferSize, 2, 0);
- } else {
- writeFile = hdfsOpenFile(fs, writeFileName, O_WRONLY | O_APPEND,
- bufferSize, 2, 0);
- }
- if (!writeFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", writeFileName);
- exit(1);
- }
-
- // data to be written to the file
- buffer = malloc(sizeof(char) * bufferSize + 1);
- if(buffer == NULL) {
- fprintf(stderr, "Could not allocate buffer of size %d\n", bufferSize);
- exit(1);
- }
- for (i = 0; i < bufferSize; ++i) {
- buffer[i] = 'a' + (i%26);
- }
- buffer[bufferSize] = '\0';
-
- // write to the file
- totalWriteSize = 0;
- for (; totalWriteSize < fileTotalSize; ) {
- toWrite = bufferSize < (fileTotalSize - totalWriteSize) ?
- bufferSize : (fileTotalSize - totalWriteSize);
- written = hdfsWrite(fs, writeFile, (void*)buffer, toWrite);
- fprintf(stderr, "written size %d, to write size %d\n",
- written, toWrite);
- totalWriteSize += written;
- }
-
- // cleanup
- free(buffer);
- hdfsCloseFile(fs, writeFile);
- fprintf(stderr, "file total size: %" PRId64 ", total write size: %d\n",
- fileTotalSize, totalWriteSize);
- hdfsDisconnect(fs);
-
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/CMakeLists.txt b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/CMakeLists.txt
deleted file mode 100644
index 7a5e5a1..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/CMakeLists.txt
+++ /dev/null
@@ -1,102 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-set(CMAKE_SKIP_RPATH TRUE)
-
-# Flatten a list into a string.
-function(flatten_list INPUT SEPARATOR OUTPUT)
- string (REPLACE ";" "${SEPARATOR}" _TMPS "${INPUT}")
- set (${OUTPUT} "${_TMPS}" PARENT_SCOPE)
-endfunction()
-
-# Find Linux FUSE
-if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
- find_package(PkgConfig REQUIRED)
- pkg_check_modules(FUSE fuse)
- if(FUSE_FOUND)
- flatten_list("${FUSE_CFLAGS}" " " FUSE_CFLAGS)
- flatten_list("${FUSE_LDFLAGS}" " " FUSE_LDFLAGS)
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${FUSE_CFLAGS}")
- set(CMAKE_LD_FLAGS "${CMAKE_LD_FLAGS} ${FUSE_LDFLAGS}")
- message(STATUS "Building Linux FUSE client.")
- include_directories(${FUSE_INCLUDE_DIRS})
- else()
- message(STATUS "Failed to find Linux FUSE libraries or include files. Will not build FUSE client.")
- endif(FUSE_FOUND)
-else()
- message(STATUS "Non-Linux system detected. Will not build FUSE client.")
-endif()
-
-if(FUSE_FOUND)
- add_library(posix_util
- ../util/posix_util.c
- )
-
- add_executable(fuse_dfs
- fuse_dfs.c
- fuse_options.c
- fuse_connect.c
- fuse_impls_access.c
- fuse_impls_chmod.c
- fuse_impls_chown.c
- fuse_impls_create.c
- fuse_impls_flush.c
- fuse_impls_getattr.c
- fuse_impls_mkdir.c
- fuse_impls_mknod.c
- fuse_impls_open.c
- fuse_impls_read.c
- fuse_impls_readdir.c
- fuse_impls_release.c
- fuse_impls_rename.c
- fuse_impls_rmdir.c
- fuse_impls_statfs.c
- fuse_impls_symlink.c
- fuse_impls_truncate.c
- fuse_impls_unlink.c
- fuse_impls_utimens.c
- fuse_impls_write.c
- fuse_init.c
- fuse_stat_struct.c
- fuse_trash.c
- fuse_users.c
- )
- target_link_libraries(fuse_dfs
- ${FUSE_LIBRARIES}
- ${JAVA_JVM_LIBRARY}
- hdfs
- m
- pthread
- rt
- )
- add_executable(test_fuse_dfs
- test/test_fuse_dfs.c
- test/fuse_workload.c
- )
- target_link_libraries(test_fuse_dfs
- ${FUSE_LIBRARIES}
- native_mini_dfs
- posix_util
- pthread
- )
- set(REQUIRE_FUSE ${REQUIRE_FUSE}) # Prevent unused variable warning
-else()
- if(REQUIRE_FUSE)
- message(FATAL_ERROR "Required component fuse_dfs could not be built.")
- endif()
-endif()
[15/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/vecsum.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/vecsum.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/vecsum.c
new file mode 100644
index 0000000..80a64b4
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/vecsum.c
@@ -0,0 +1,825 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+#ifdef __MACH__ // OS X does not have clock_gettime
+#include <mach/clock.h>
+#include <mach/mach.h>
+#include <mach/mach_time.h>
+#endif
+
+#include "config.h"
+#include "hdfs.h"
+
+#define VECSUM_CHUNK_SIZE (8 * 1024 * 1024)
+#define ZCR_READ_CHUNK_SIZE (1024 * 1024 * 8)
+#define NORMAL_READ_CHUNK_SIZE (8 * 1024 * 1024)
+#define DOUBLES_PER_LOOP_ITER 16
+
+static double timespec_to_double(const struct timespec *ts)
+{
+ double sec = ts->tv_sec;
+ double nsec = ts->tv_nsec;
+ return sec + (nsec / 1000000000L);
+}
+
+struct stopwatch {
+ struct timespec start;
+ struct timespec stop;
+};
+
+
+#ifdef __MACH__
+static int clock_gettime_mono(struct timespec * ts) {
+ static mach_timebase_info_data_t tb;
+ static uint64_t timestart = 0;
+ uint64_t t = 0;
+ if (timestart == 0) {
+ mach_timebase_info(&tb);
+ timestart = mach_absolute_time();
+ }
+ t = mach_absolute_time() - timestart;
+ t *= tb.numer;
+ t /= tb.denom;
+ ts->tv_sec = t / 1000000000ULL;
+ ts->tv_nsec = t - (ts->tv_sec * 1000000000ULL);
+ return 0;
+}
+#else
+static int clock_gettime_mono(struct timespec * ts) {
+ return clock_gettime(CLOCK_MONOTONIC, ts);
+}
+#endif
+
+static struct stopwatch *stopwatch_create(void)
+{
+ struct stopwatch *watch;
+
+ watch = calloc(1, sizeof(struct stopwatch));
+ if (!watch) {
+ fprintf(stderr, "failed to allocate memory for stopwatch\n");
+ goto error;
+ }
+ if (clock_gettime_mono(&watch->start)) {
+ int err = errno;
+ fprintf(stderr, "clock_gettime(CLOCK_MONOTONIC) failed with "
+ "error %d (%s)\n", err, strerror(err));
+ goto error;
+ }
+ return watch;
+
+error:
+ free(watch);
+ return NULL;
+}
+
+static void stopwatch_stop(struct stopwatch *watch,
+ long long bytes_read)
+{
+ double elapsed, rate;
+
+ if (clock_gettime_mono(&watch->stop)) {
+ int err = errno;
+ fprintf(stderr, "clock_gettime(CLOCK_MONOTONIC) failed with "
+ "error %d (%s)\n", err, strerror(err));
+ goto done;
+ }
+ elapsed = timespec_to_double(&watch->stop) -
+ timespec_to_double(&watch->start);
+ rate = (bytes_read / elapsed) / (1024 * 1024 * 1024);
+ printf("stopwatch: took %.5g seconds to read %lld bytes, "
+ "for %.5g GB/s\n", elapsed, bytes_read, rate);
+ printf("stopwatch: %.5g seconds\n", elapsed);
+done:
+ free(watch);
+}
+
+enum vecsum_type {
+ VECSUM_LOCAL = 0,
+ VECSUM_LIBHDFS,
+ VECSUM_ZCR,
+};
+
+#define VECSUM_TYPE_VALID_VALUES "libhdfs, zcr, or local"
+
+int parse_vecsum_type(const char *str)
+{
+ if (strcasecmp(str, "local") == 0)
+ return VECSUM_LOCAL;
+ else if (strcasecmp(str, "libhdfs") == 0)
+ return VECSUM_LIBHDFS;
+ else if (strcasecmp(str, "zcr") == 0)
+ return VECSUM_ZCR;
+ else
+ return -1;
+}
+
+struct options {
+ // The path to read.
+ const char *path;
+
+ // Length of the file.
+ long long length;
+
+ // The number of times to read the path.
+ int passes;
+
+ // Type of vecsum to do
+ enum vecsum_type ty;
+
+ // RPC address to use for HDFS
+ const char *rpc_address;
+};
+
+static struct options *options_create(void)
+{
+ struct options *opts = NULL;
+ const char *pass_str;
+ const char *ty_str;
+ const char *length_str;
+ int ty;
+
+ opts = calloc(1, sizeof(struct options));
+ if (!opts) {
+ fprintf(stderr, "failed to calloc options\n");
+ goto error;
+ }
+ opts->path = getenv("VECSUM_PATH");
+ if (!opts->path) {
+ fprintf(stderr, "You must set the VECSUM_PATH environment "
+ "variable to the path of the file to read.\n");
+ goto error;
+ }
+ length_str = getenv("VECSUM_LENGTH");
+ if (!length_str) {
+ length_str = "2147483648";
+ }
+ opts->length = atoll(length_str);
+ if (!opts->length) {
+ fprintf(stderr, "Can't parse VECSUM_LENGTH of '%s'.\n",
+ length_str);
+ goto error;
+ }
+ if (opts->length % VECSUM_CHUNK_SIZE) {
+ fprintf(stderr, "VECSUM_LENGTH must be a multiple of '%lld'. The "
+ "currently specified length of '%lld' is not.\n",
+ (long long)VECSUM_CHUNK_SIZE, (long long)opts->length);
+ goto error;
+ }
+ pass_str = getenv("VECSUM_PASSES");
+ if (!pass_str) {
+ fprintf(stderr, "You must set the VECSUM_PASSES environment "
+ "variable to the number of passes to make.\n");
+ goto error;
+ }
+ opts->passes = atoi(pass_str);
+ if (opts->passes <= 0) {
+ fprintf(stderr, "Invalid value for the VECSUM_PASSES "
+ "environment variable. You must set this to a "
+ "number greater than 0.\n");
+ goto error;
+ }
+ ty_str = getenv("VECSUM_TYPE");
+ if (!ty_str) {
+ fprintf(stderr, "You must set the VECSUM_TYPE environment "
+ "variable to " VECSUM_TYPE_VALID_VALUES "\n");
+ goto error;
+ }
+ ty = parse_vecsum_type(ty_str);
+ if (ty < 0) {
+ fprintf(stderr, "Invalid VECSUM_TYPE environment variable. "
+ "Valid values are " VECSUM_TYPE_VALID_VALUES "\n");
+ goto error;
+ }
+ opts->ty = ty;
+ opts->rpc_address = getenv("VECSUM_RPC_ADDRESS");
+ if (!opts->rpc_address) {
+ opts->rpc_address = "default";
+ }
+ return opts;
+error:
+ free(opts);
+ return NULL;
+}
+
+static int test_file_chunk_setup(double **chunk)
+{
+ int i;
+ double *c, val;
+
+ c = malloc(VECSUM_CHUNK_SIZE);
+ if (!c) {
+ fprintf(stderr, "test_file_create: failed to malloc "
+ "a buffer of size '%lld'\n",
+ (long long) VECSUM_CHUNK_SIZE);
+ return EIO;
+ }
+ val = 0.0;
+ for (i = 0; i < VECSUM_CHUNK_SIZE / sizeof(double); i++) {
+ c[i] = val;
+ val += 0.5;
+ }
+ *chunk = c;
+ return 0;
+}
+
+static void options_free(struct options *opts)
+{
+ free(opts);
+}
+
+struct local_data {
+ int fd;
+ double *mmap;
+ long long length;
+};
+
+static int local_data_create_file(struct local_data *cdata,
+ const struct options *opts)
+{
+ int ret = EIO;
+ int dup_fd = -1;
+ FILE *fp = NULL;
+ double *chunk = NULL;
+ long long offset = 0;
+
+ dup_fd = dup(cdata->fd);
+ if (dup_fd < 0) {
+ ret = errno;
+ fprintf(stderr, "local_data_create_file: dup failed: %s (%d)\n",
+ strerror(ret), ret);
+ goto done;
+ }
+ fp = fdopen(dup_fd, "w");
+ if (!fp) {
+ ret = errno;
+ fprintf(stderr, "local_data_create_file: fdopen failed: %s (%d)\n",
+ strerror(ret), ret);
+ goto done;
+ }
+ ret = test_file_chunk_setup(&chunk);
+ if (ret)
+ goto done;
+ while (offset < opts->length) {
+ if (fwrite(chunk, VECSUM_CHUNK_SIZE, 1, fp) != 1) {
+ fprintf(stderr, "local_data_create_file: failed to write to "
+ "the local file '%s' at offset %lld\n",
+ opts->path, offset);
+ ret = EIO;
+ goto done;
+ }
+ offset += VECSUM_CHUNK_SIZE;
+ }
+ fprintf(stderr, "local_data_create_file: successfully re-wrote %s as "
+ "a file of length %lld\n", opts->path, opts->length);
+ ret = 0;
+
+done:
+ if (dup_fd >= 0) {
+ close(dup_fd);
+ }
+ if (fp) {
+ fclose(fp);
+ }
+ free(chunk);
+ return ret;
+}
+
+static struct local_data *local_data_create(const struct options *opts)
+{
+ struct local_data *cdata = NULL;
+ struct stat st_buf;
+
+ cdata = malloc(sizeof(*cdata));
+ if (!cdata) {
+ fprintf(stderr, "Failed to allocate local test data.\n");
+ goto error;
+ }
+ cdata->fd = -1;
+ cdata->mmap = MAP_FAILED;
+ cdata->length = opts->length;
+
+ cdata->fd = open(opts->path, O_RDWR | O_CREAT, 0777);
+ if (cdata->fd < 0) {
+ int err = errno;
+ fprintf(stderr, "local_data_create: failed to open %s "
+ "for read/write: error %d (%s)\n", opts->path, err, strerror(err));
+ goto error;
+ }
+ if (fstat(cdata->fd, &st_buf)) {
+ int err = errno;
+ fprintf(stderr, "local_data_create: fstat(%s) failed: "
+ "error %d (%s)\n", opts->path, err, strerror(err));
+ goto error;
+ }
+ if (st_buf.st_size != opts->length) {
+ int err;
+ fprintf(stderr, "local_data_create: current size of %s is %lld, but "
+ "we want %lld. Re-writing the file.\n",
+ opts->path, (long long)st_buf.st_size,
+ (long long)opts->length);
+ err = local_data_create_file(cdata, opts);
+ if (err)
+ goto error;
+ }
+ cdata->mmap = mmap(NULL, cdata->length, PROT_READ,
+ MAP_PRIVATE, cdata->fd, 0);
+ if (cdata->mmap == MAP_FAILED) {
+ int err = errno;
+ fprintf(stderr, "local_data_create: mmap(%s) failed: "
+ "error %d (%s)\n", opts->path, err, strerror(err));
+ goto error;
+ }
+ return cdata;
+
+error:
+ if (cdata) {
+ if (cdata->fd >= 0) {
+ close(cdata->fd);
+ }
+ free(cdata);
+ }
+ return NULL;
+}
+
+static void local_data_free(struct local_data *cdata)
+{
+ close(cdata->fd);
+ munmap(cdata->mmap, cdata->length);
+}
+
+struct libhdfs_data {
+ hdfsFS fs;
+ hdfsFile file;
+ long long length;
+ double *buf;
+};
+
+static void libhdfs_data_free(struct libhdfs_data *ldata)
+{
+ if (ldata->fs) {
+ free(ldata->buf);
+ if (ldata->file) {
+ hdfsCloseFile(ldata->fs, ldata->file);
+ }
+ hdfsDisconnect(ldata->fs);
+ }
+ free(ldata);
+}
+
+static int libhdfs_data_create_file(struct libhdfs_data *ldata,
+ const struct options *opts)
+{
+ int ret;
+ double *chunk = NULL;
+ long long offset = 0;
+
+ ldata->file = hdfsOpenFile(ldata->fs, opts->path, O_WRONLY, 0, 1, 0);
+ if (!ldata->file) {
+ ret = errno;
+ fprintf(stderr, "libhdfs_data_create_file: hdfsOpenFile(%s, "
+ "O_WRONLY) failed: error %d (%s)\n", opts->path, ret,
+ strerror(ret));
+ goto done;
+ }
+ ret = test_file_chunk_setup(&chunk);
+ if (ret)
+ goto done;
+ while (offset < opts->length) {
+ ret = hdfsWrite(ldata->fs, ldata->file, chunk, VECSUM_CHUNK_SIZE);
+ if (ret < 0) {
+ ret = errno;
+ fprintf(stderr, "libhdfs_data_create_file: got error %d (%s) at "
+ "offset %lld of %s\n", ret, strerror(ret),
+ offset, opts->path);
+ goto done;
+ } else if (ret < VECSUM_CHUNK_SIZE) {
+ fprintf(stderr, "libhdfs_data_create_file: got short write "
+ "of %d at offset %lld of %s\n", ret, offset, opts->path);
+ goto done;
+ }
+ offset += VECSUM_CHUNK_SIZE;
+ }
+ ret = 0;
+done:
+ free(chunk);
+ if (ldata->file) {
+ if (hdfsCloseFile(ldata->fs, ldata->file)) {
+ fprintf(stderr, "libhdfs_data_create_file: hdfsCloseFile error.");
+ ret = EIO;
+ }
+ ldata->file = NULL;
+ }
+ return ret;
+}
+
+static struct libhdfs_data *libhdfs_data_create(const struct options *opts)
+{
+ struct libhdfs_data *ldata = NULL;
+ struct hdfsBuilder *builder = NULL;
+ hdfsFileInfo *pinfo = NULL;
+
+ ldata = calloc(1, sizeof(struct libhdfs_data));
+ if (!ldata) {
+ fprintf(stderr, "Failed to allocate libhdfs test data.\n");
+ goto error;
+ }
+ builder = hdfsNewBuilder();
+ if (!builder) {
+ fprintf(stderr, "Failed to create builder.\n");
+ goto error;
+ }
+ hdfsBuilderSetNameNode(builder, opts->rpc_address);
+ hdfsBuilderConfSetStr(builder,
+ "dfs.client.read.shortcircuit.skip.checksum", "true");
+ ldata->fs = hdfsBuilderConnect(builder);
+ if (!ldata->fs) {
+ fprintf(stderr, "Could not connect to default namenode!\n");
+ goto error;
+ }
+ pinfo = hdfsGetPathInfo(ldata->fs, opts->path);
+ if (!pinfo) {
+ int err = errno;
+ fprintf(stderr, "hdfsGetPathInfo(%s) failed: error %d (%s). "
+ "Attempting to re-create file.\n",
+ opts->path, err, strerror(err));
+ if (libhdfs_data_create_file(ldata, opts))
+ goto error;
+ } else if (pinfo->mSize != opts->length) {
+ fprintf(stderr, "hdfsGetPathInfo(%s) failed: length was %lld, "
+ "but we want length %lld. Attempting to re-create file.\n",
+ opts->path, (long long)pinfo->mSize, (long long)opts->length);
+ if (libhdfs_data_create_file(ldata, opts))
+ goto error;
+ }
+ ldata->file = hdfsOpenFile(ldata->fs, opts->path, O_RDONLY, 0, 0, 0);
+ if (!ldata->file) {
+ int err = errno;
+ fprintf(stderr, "hdfsOpenFile(%s) failed: error %d (%s)\n",
+ opts->path, err, strerror(err));
+ goto error;
+ }
+ ldata->length = opts->length;
+ return ldata;
+
+error:
+ if (pinfo)
+ hdfsFreeFileInfo(pinfo, 1);
+ if (ldata)
+ libhdfs_data_free(ldata);
+ return NULL;
+}
+
+static int check_byte_size(int byte_size, const char *const str)
+{
+ if (byte_size % sizeof(double)) {
+ fprintf(stderr, "%s is not a multiple "
+ "of sizeof(double)\n", str);
+ return EINVAL;
+ }
+ if ((byte_size / sizeof(double)) % DOUBLES_PER_LOOP_ITER) {
+ fprintf(stderr, "The number of doubles contained in "
+ "%s is not a multiple of DOUBLES_PER_LOOP_ITER\n",
+ str);
+ return EINVAL;
+ }
+ return 0;
+}
+
+#ifdef HAVE_INTEL_SSE_INTRINSICS
+
+#include <emmintrin.h>
+
+static double vecsum(const double *buf, int num_doubles)
+{
+ int i;
+ double hi, lo;
+ __m128d x0, x1, x2, x3, x4, x5, x6, x7;
+ __m128d sum0 = _mm_set_pd(0.0,0.0);
+ __m128d sum1 = _mm_set_pd(0.0,0.0);
+ __m128d sum2 = _mm_set_pd(0.0,0.0);
+ __m128d sum3 = _mm_set_pd(0.0,0.0);
+ __m128d sum4 = _mm_set_pd(0.0,0.0);
+ __m128d sum5 = _mm_set_pd(0.0,0.0);
+ __m128d sum6 = _mm_set_pd(0.0,0.0);
+ __m128d sum7 = _mm_set_pd(0.0,0.0);
+ for (i = 0; i < num_doubles; i+=DOUBLES_PER_LOOP_ITER) {
+ x0 = _mm_load_pd(buf + i + 0);
+ x1 = _mm_load_pd(buf + i + 2);
+ x2 = _mm_load_pd(buf + i + 4);
+ x3 = _mm_load_pd(buf + i + 6);
+ x4 = _mm_load_pd(buf + i + 8);
+ x5 = _mm_load_pd(buf + i + 10);
+ x6 = _mm_load_pd(buf + i + 12);
+ x7 = _mm_load_pd(buf + i + 14);
+ sum0 = _mm_add_pd(sum0, x0);
+ sum1 = _mm_add_pd(sum1, x1);
+ sum2 = _mm_add_pd(sum2, x2);
+ sum3 = _mm_add_pd(sum3, x3);
+ sum4 = _mm_add_pd(sum4, x4);
+ sum5 = _mm_add_pd(sum5, x5);
+ sum6 = _mm_add_pd(sum6, x6);
+ sum7 = _mm_add_pd(sum7, x7);
+ }
+ x0 = _mm_add_pd(sum0, sum1);
+ x1 = _mm_add_pd(sum2, sum3);
+ x2 = _mm_add_pd(sum4, sum5);
+ x3 = _mm_add_pd(sum6, sum7);
+ x4 = _mm_add_pd(x0, x1);
+ x5 = _mm_add_pd(x2, x3);
+ x6 = _mm_add_pd(x4, x5);
+ _mm_storeh_pd(&hi, x6);
+ _mm_storel_pd(&lo, x6);
+ return hi + lo;
+}
+
+#else
+
+static double vecsum(const double *buf, int num_doubles)
+{
+ int i;
+ double sum = 0.0;
+ for (i = 0; i < num_doubles; i++) {
+ sum += buf[i];
+ }
+ return sum;
+}
+
+#endif
+
+static int vecsum_zcr_loop(int pass, struct libhdfs_data *ldata,
+ struct hadoopRzOptions *zopts,
+ const struct options *opts)
+{
+ int32_t len;
+ double sum = 0.0;
+ const double *buf;
+ struct hadoopRzBuffer *rzbuf = NULL;
+ int ret;
+
+ while (1) {
+ rzbuf = hadoopReadZero(ldata->file, zopts, ZCR_READ_CHUNK_SIZE);
+ if (!rzbuf) {
+ ret = errno;
+ fprintf(stderr, "hadoopReadZero failed with error "
+ "code %d (%s)\n", ret, strerror(ret));
+ goto done;
+ }
+ buf = hadoopRzBufferGet(rzbuf);
+ if (!buf) break;
+ len = hadoopRzBufferLength(rzbuf);
+ if (len < ZCR_READ_CHUNK_SIZE) {
+ fprintf(stderr, "hadoopReadZero got a partial read "
+ "of length %d\n", len);
+ ret = EINVAL;
+ goto done;
+ }
+ sum += vecsum(buf,
+ ZCR_READ_CHUNK_SIZE / sizeof(double));
+ hadoopRzBufferFree(ldata->file, rzbuf);
+ }
+ printf("finished zcr pass %d. sum = %g\n", pass, sum);
+ ret = 0;
+
+done:
+ if (rzbuf)
+ hadoopRzBufferFree(ldata->file, rzbuf);
+ return ret;
+}
+
+static int vecsum_zcr(struct libhdfs_data *ldata,
+ const struct options *opts)
+{
+ int ret, pass;
+ struct hadoopRzOptions *zopts = NULL;
+
+ zopts = hadoopRzOptionsAlloc();
+ if (!zopts) {
+ fprintf(stderr, "hadoopRzOptionsAlloc failed.\n");
+ ret = ENOMEM;
+ goto done;
+ }
+ if (hadoopRzOptionsSetSkipChecksum(zopts, 1)) {
+ ret = errno;
+ perror("hadoopRzOptionsSetSkipChecksum failed: ");
+ goto done;
+ }
+ if (hadoopRzOptionsSetByteBufferPool(zopts, NULL)) {
+ ret = errno;
+ perror("hadoopRzOptionsSetByteBufferPool failed: ");
+ goto done;
+ }
+ for (pass = 0; pass < opts->passes; ++pass) {
+ ret = vecsum_zcr_loop(pass, ldata, zopts, opts);
+ if (ret) {
+ fprintf(stderr, "vecsum_zcr_loop pass %d failed "
+ "with error %d\n", pass, ret);
+ goto done;
+ }
+ hdfsSeek(ldata->fs, ldata->file, 0);
+ }
+ ret = 0;
+done:
+ if (zopts)
+ hadoopRzOptionsFree(zopts);
+ return ret;
+}
+
+tSize hdfsReadFully(hdfsFS fs, hdfsFile f, void* buffer, tSize length)
+{
+ uint8_t *buf = buffer;
+ tSize ret, nread = 0;
+
+ while (length > 0) {
+ ret = hdfsRead(fs, f, buf, length);
+ if (ret < 0) {
+ if (errno != EINTR) {
+ return -1;
+ }
+ }
+ if (ret == 0) {
+ break;
+ }
+ nread += ret;
+ length -= ret;
+ buf += ret;
+ }
+ return nread;
+}
+
+static int vecsum_normal_loop(int pass, const struct libhdfs_data *ldata,
+ const struct options *opts)
+{
+ double sum = 0.0;
+
+ while (1) {
+ int res = hdfsReadFully(ldata->fs, ldata->file, ldata->buf,
+ NORMAL_READ_CHUNK_SIZE);
+ if (res == 0) // EOF
+ break;
+ if (res < 0) {
+ int err = errno;
+ fprintf(stderr, "hdfsRead failed with error %d (%s)\n",
+ err, strerror(err));
+ return err;
+ }
+ if (res < NORMAL_READ_CHUNK_SIZE) {
+ fprintf(stderr, "hdfsRead got a partial read of "
+ "length %d\n", res);
+ return EINVAL;
+ }
+ sum += vecsum(ldata->buf,
+ NORMAL_READ_CHUNK_SIZE / sizeof(double));
+ }
+ printf("finished normal pass %d. sum = %g\n", pass, sum);
+ return 0;
+}
+
+static int vecsum_libhdfs(struct libhdfs_data *ldata,
+ const struct options *opts)
+{
+ int pass;
+
+ ldata->buf = malloc(NORMAL_READ_CHUNK_SIZE);
+ if (!ldata->buf) {
+ fprintf(stderr, "failed to malloc buffer of size %d\n",
+ NORMAL_READ_CHUNK_SIZE);
+ return ENOMEM;
+ }
+ for (pass = 0; pass < opts->passes; ++pass) {
+ int ret = vecsum_normal_loop(pass, ldata, opts);
+ if (ret) {
+ fprintf(stderr, "vecsum_normal_loop pass %d failed "
+ "with error %d\n", pass, ret);
+ return ret;
+ }
+ hdfsSeek(ldata->fs, ldata->file, 0);
+ }
+ return 0;
+}
+
+static void vecsum_local(struct local_data *cdata, const struct options *opts)
+{
+ int pass;
+
+ for (pass = 0; pass < opts->passes; pass++) {
+ double sum = vecsum(cdata->mmap, cdata->length / sizeof(double));
+ printf("finished vecsum_local pass %d. sum = %g\n", pass, sum);
+ }
+}
+
+static long long vecsum_length(const struct options *opts,
+ const struct libhdfs_data *ldata)
+{
+ if (opts->ty == VECSUM_LOCAL) {
+ struct stat st_buf = { 0 };
+ if (stat(opts->path, &st_buf)) {
+ int err = errno;
+ fprintf(stderr, "vecsum_length: stat(%s) failed: "
+ "error %d (%s)\n", opts->path, err, strerror(err));
+ return -EIO;
+ }
+ return st_buf.st_size;
+ } else {
+ return ldata->length;
+ }
+}
+
+/*
+ * vecsum is a microbenchmark which measures the speed of various ways of
+ * reading from HDFS. It creates a file containing floating-point 'doubles',
+ * and computes the sum of all the doubles several times. For some CPUs,
+ * assembly optimizations are used for the summation (SSE, etc).
+ */
+int main(void)
+{
+ int ret = 1;
+ struct options *opts = NULL;
+ struct local_data *cdata = NULL;
+ struct libhdfs_data *ldata = NULL;
+ struct stopwatch *watch = NULL;
+
+ if (check_byte_size(VECSUM_CHUNK_SIZE, "VECSUM_CHUNK_SIZE") ||
+ check_byte_size(ZCR_READ_CHUNK_SIZE,
+ "ZCR_READ_CHUNK_SIZE") ||
+ check_byte_size(NORMAL_READ_CHUNK_SIZE,
+ "NORMAL_READ_CHUNK_SIZE")) {
+ goto done;
+ }
+ opts = options_create();
+ if (!opts)
+ goto done;
+ if (opts->ty == VECSUM_LOCAL) {
+ cdata = local_data_create(opts);
+ if (!cdata)
+ goto done;
+ } else {
+ ldata = libhdfs_data_create(opts);
+ if (!ldata)
+ goto done;
+ }
+ watch = stopwatch_create();
+ if (!watch)
+ goto done;
+ switch (opts->ty) {
+ case VECSUM_LOCAL:
+ vecsum_local(cdata, opts);
+ ret = 0;
+ break;
+ case VECSUM_LIBHDFS:
+ ret = vecsum_libhdfs(ldata, opts);
+ break;
+ case VECSUM_ZCR:
+ ret = vecsum_zcr(ldata, opts);
+ break;
+ }
+ if (ret) {
+ fprintf(stderr, "vecsum failed with error %d\n", ret);
+ goto done;
+ }
+ ret = 0;
+done:
+ fprintf(stderr, "cleaning up...\n");
+ if (watch && (ret == 0)) {
+ long long length = vecsum_length(opts, ldata);
+ if (length >= 0) {
+ stopwatch_stop(watch, length * opts->passes);
+ }
+ }
+ if (cdata)
+ local_data_free(cdata);
+ if (ldata)
+ libhdfs_data_free(ldata);
+ if (opts)
+ options_free(opts);
+ return ret;
+}
+
+// vim: ts=4:sw=4:tw=79:et
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test_libhdfs_threaded.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test_libhdfs_threaded.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test_libhdfs_threaded.c
new file mode 100644
index 0000000..702430c
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test_libhdfs_threaded.c
@@ -0,0 +1,360 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "expect.h"
+#include "hdfs.h"
+#include "native_mini_dfs.h"
+#include "os/thread.h"
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define TO_STR_HELPER(X) #X
+#define TO_STR(X) TO_STR_HELPER(X)
+
+#define TLH_MAX_THREADS 100
+
+#define TLH_DEFAULT_BLOCK_SIZE 134217728
+
+static struct NativeMiniDfsCluster* tlhCluster;
+
+struct tlhThreadInfo {
+ /** Thread index */
+ int threadIdx;
+ /** 0 = thread was successful; error code otherwise */
+ int success;
+ /** thread identifier */
+ thread theThread;
+};
+
+static int hdfsSingleNameNodeConnect(struct NativeMiniDfsCluster *cl, hdfsFS *fs,
+ const char *username)
+{
+ int ret;
+ tPort port;
+ hdfsFS hdfs;
+ struct hdfsBuilder *bld;
+
+ port = (tPort)nmdGetNameNodePort(cl);
+ if (port < 0) {
+ fprintf(stderr, "hdfsSingleNameNodeConnect: nmdGetNameNodePort "
+ "returned error %d\n", port);
+ return port;
+ }
+ bld = hdfsNewBuilder();
+ if (!bld)
+ return -ENOMEM;
+ hdfsBuilderSetForceNewInstance(bld);
+ hdfsBuilderSetNameNode(bld, "localhost");
+ hdfsBuilderSetNameNodePort(bld, port);
+ hdfsBuilderConfSetStr(bld, "dfs.block.size",
+ TO_STR(TLH_DEFAULT_BLOCK_SIZE));
+ hdfsBuilderConfSetStr(bld, "dfs.blocksize",
+ TO_STR(TLH_DEFAULT_BLOCK_SIZE));
+ if (username) {
+ hdfsBuilderSetUserName(bld, username);
+ }
+ hdfs = hdfsBuilderConnect(bld);
+ if (!hdfs) {
+ ret = -errno;
+ return ret;
+ }
+ *fs = hdfs;
+ return 0;
+}
+
+static int doTestGetDefaultBlockSize(hdfsFS fs, const char *path)
+{
+ int64_t blockSize;
+ int ret;
+
+ blockSize = hdfsGetDefaultBlockSize(fs);
+ if (blockSize < 0) {
+ ret = errno;
+ fprintf(stderr, "hdfsGetDefaultBlockSize failed with error %d\n", ret);
+ return ret;
+ } else if (blockSize != TLH_DEFAULT_BLOCK_SIZE) {
+ fprintf(stderr, "hdfsGetDefaultBlockSize got %"PRId64", but we "
+ "expected %d\n", blockSize, TLH_DEFAULT_BLOCK_SIZE);
+ return EIO;
+ }
+
+ blockSize = hdfsGetDefaultBlockSizeAtPath(fs, path);
+ if (blockSize < 0) {
+ ret = errno;
+ fprintf(stderr, "hdfsGetDefaultBlockSizeAtPath(%s) failed with "
+ "error %d\n", path, ret);
+ return ret;
+ } else if (blockSize != TLH_DEFAULT_BLOCK_SIZE) {
+ fprintf(stderr, "hdfsGetDefaultBlockSizeAtPath(%s) got "
+ "%"PRId64", but we expected %d\n",
+ path, blockSize, TLH_DEFAULT_BLOCK_SIZE);
+ return EIO;
+ }
+ return 0;
+}
+
+struct tlhPaths {
+ char prefix[256];
+ char file1[256];
+ char file2[256];
+};
+
+static int setupPaths(const struct tlhThreadInfo *ti, struct tlhPaths *paths)
+{
+ memset(paths, 0, sizeof(*paths));
+ if (snprintf(paths->prefix, sizeof(paths->prefix), "/tlhData%04d",
+ ti->threadIdx) >= sizeof(paths->prefix)) {
+ return ENAMETOOLONG;
+ }
+ if (snprintf(paths->file1, sizeof(paths->file1), "%s/file1",
+ paths->prefix) >= sizeof(paths->file1)) {
+ return ENAMETOOLONG;
+ }
+ if (snprintf(paths->file2, sizeof(paths->file2), "%s/file2",
+ paths->prefix) >= sizeof(paths->file2)) {
+ return ENAMETOOLONG;
+ }
+ return 0;
+}
+
+static int doTestHdfsOperations(struct tlhThreadInfo *ti, hdfsFS fs,
+ const struct tlhPaths *paths)
+{
+ char tmp[4096];
+ hdfsFile file;
+ int ret, expected, numEntries;
+ hdfsFileInfo *fileInfo;
+ struct hdfsReadStatistics *readStats = NULL;
+
+ if (hdfsExists(fs, paths->prefix) == 0) {
+ EXPECT_ZERO(hdfsDelete(fs, paths->prefix, 1));
+ }
+ EXPECT_ZERO(hdfsCreateDirectory(fs, paths->prefix));
+
+ EXPECT_ZERO(doTestGetDefaultBlockSize(fs, paths->prefix));
+
+ /* There should be no entry in the directory. */
+ errno = EACCES; // see if errno is set to 0 on success
+ EXPECT_NULL_WITH_ERRNO(hdfsListDirectory(fs, paths->prefix, &numEntries), 0);
+ if (numEntries != 0) {
+ fprintf(stderr, "hdfsListDirectory set numEntries to "
+ "%d on empty directory.", numEntries);
+ }
+
+ /* There should not be any file to open for reading. */
+ EXPECT_NULL(hdfsOpenFile(fs, paths->file1, O_RDONLY, 0, 0, 0));
+
+ /* hdfsOpenFile should not accept mode = 3 */
+ EXPECT_NULL(hdfsOpenFile(fs, paths->file1, 3, 0, 0, 0));
+
+ file = hdfsOpenFile(fs, paths->file1, O_WRONLY, 0, 0, 0);
+ EXPECT_NONNULL(file);
+
+ /* TODO: implement writeFully and use it here */
+ expected = (int)strlen(paths->prefix);
+ ret = hdfsWrite(fs, file, paths->prefix, expected);
+ if (ret < 0) {
+ ret = errno;
+ fprintf(stderr, "hdfsWrite failed and set errno %d\n", ret);
+ return ret;
+ }
+ if (ret != expected) {
+ fprintf(stderr, "hdfsWrite was supposed to write %d bytes, but "
+ "it wrote %d\n", ret, expected);
+ return EIO;
+ }
+ EXPECT_ZERO(hdfsFlush(fs, file));
+ EXPECT_ZERO(hdfsHSync(fs, file));
+ EXPECT_ZERO(hdfsCloseFile(fs, file));
+
+ /* There should be 1 entry in the directory. */
+ EXPECT_NONNULL(hdfsListDirectory(fs, paths->prefix, &numEntries));
+ if (numEntries != 1) {
+ fprintf(stderr, "hdfsListDirectory set numEntries to "
+ "%d on directory containing 1 file.", numEntries);
+ }
+
+ /* Let's re-open the file for reading */
+ file = hdfsOpenFile(fs, paths->file1, O_RDONLY, 0, 0, 0);
+ EXPECT_NONNULL(file);
+
+ EXPECT_ZERO(hdfsFileGetReadStatistics(file, &readStats));
+ errno = 0;
+ EXPECT_UINT64_EQ(UINT64_C(0), readStats->totalBytesRead);
+ EXPECT_UINT64_EQ(UINT64_C(0), readStats->totalLocalBytesRead);
+ EXPECT_UINT64_EQ(UINT64_C(0), readStats->totalShortCircuitBytesRead);
+ hdfsFileFreeReadStatistics(readStats);
+ /* TODO: implement readFully and use it here */
+ ret = hdfsRead(fs, file, tmp, sizeof(tmp));
+ if (ret < 0) {
+ ret = errno;
+ fprintf(stderr, "hdfsRead failed and set errno %d\n", ret);
+ return ret;
+ }
+ if (ret != expected) {
+ fprintf(stderr, "hdfsRead was supposed to read %d bytes, but "
+ "it read %d\n", ret, expected);
+ return EIO;
+ }
+ EXPECT_ZERO(hdfsFileGetReadStatistics(file, &readStats));
+ errno = 0;
+ EXPECT_UINT64_EQ((uint64_t)expected, readStats->totalBytesRead);
+ hdfsFileFreeReadStatistics(readStats);
+ EXPECT_ZERO(hdfsFileClearReadStatistics(file));
+ EXPECT_ZERO(hdfsFileGetReadStatistics(file, &readStats));
+ EXPECT_UINT64_EQ((uint64_t)0, readStats->totalBytesRead);
+ hdfsFileFreeReadStatistics(readStats);
+ EXPECT_ZERO(memcmp(paths->prefix, tmp, expected));
+ EXPECT_ZERO(hdfsCloseFile(fs, file));
+
+ // TODO: Non-recursive delete should fail?
+ //EXPECT_NONZERO(hdfsDelete(fs, prefix, 0));
+ EXPECT_ZERO(hdfsCopy(fs, paths->file1, fs, paths->file2));
+
+ EXPECT_ZERO(hdfsChown(fs, paths->file2, NULL, NULL));
+ EXPECT_ZERO(hdfsChown(fs, paths->file2, NULL, "doop"));
+ fileInfo = hdfsGetPathInfo(fs, paths->file2);
+ EXPECT_NONNULL(fileInfo);
+ EXPECT_ZERO(strcmp("doop", fileInfo->mGroup));
+ EXPECT_ZERO(hdfsFileIsEncrypted(fileInfo));
+ hdfsFreeFileInfo(fileInfo, 1);
+
+ EXPECT_ZERO(hdfsChown(fs, paths->file2, "ha", "doop2"));
+ fileInfo = hdfsGetPathInfo(fs, paths->file2);
+ EXPECT_NONNULL(fileInfo);
+ EXPECT_ZERO(strcmp("ha", fileInfo->mOwner));
+ EXPECT_ZERO(strcmp("doop2", fileInfo->mGroup));
+ hdfsFreeFileInfo(fileInfo, 1);
+
+ EXPECT_ZERO(hdfsChown(fs, paths->file2, "ha2", NULL));
+ fileInfo = hdfsGetPathInfo(fs, paths->file2);
+ EXPECT_NONNULL(fileInfo);
+ EXPECT_ZERO(strcmp("ha2", fileInfo->mOwner));
+ EXPECT_ZERO(strcmp("doop2", fileInfo->mGroup));
+ hdfsFreeFileInfo(fileInfo, 1);
+
+ snprintf(tmp, sizeof(tmp), "%s/nonexistent-file-name", paths->prefix);
+ EXPECT_NEGATIVE_ONE_WITH_ERRNO(hdfsChown(fs, tmp, "ha3", NULL), ENOENT);
+ return 0;
+}
+
+static int testHdfsOperationsImpl(struct tlhThreadInfo *ti)
+{
+ hdfsFS fs = NULL;
+ struct tlhPaths paths;
+
+ fprintf(stderr, "testHdfsOperations(threadIdx=%d): starting\n",
+ ti->threadIdx);
+ EXPECT_ZERO(hdfsSingleNameNodeConnect(tlhCluster, &fs, NULL));
+ EXPECT_ZERO(setupPaths(ti, &paths));
+ // test some operations
+ EXPECT_ZERO(doTestHdfsOperations(ti, fs, &paths));
+ EXPECT_ZERO(hdfsDisconnect(fs));
+ // reconnect as user "foo" and verify that we get permission errors
+ EXPECT_ZERO(hdfsSingleNameNodeConnect(tlhCluster, &fs, "foo"));
+ EXPECT_NEGATIVE_ONE_WITH_ERRNO(hdfsChown(fs, paths.file1, "ha3", NULL), EACCES);
+ EXPECT_ZERO(hdfsDisconnect(fs));
+ // reconnect to do the final delete.
+ EXPECT_ZERO(hdfsSingleNameNodeConnect(tlhCluster, &fs, NULL));
+ EXPECT_ZERO(hdfsDelete(fs, paths.prefix, 1));
+ EXPECT_ZERO(hdfsDisconnect(fs));
+ return 0;
+}
+
+static void testHdfsOperations(void *v)
+{
+ struct tlhThreadInfo *ti = (struct tlhThreadInfo*)v;
+ int ret = testHdfsOperationsImpl(ti);
+ ti->success = ret;
+}
+
+static int checkFailures(struct tlhThreadInfo *ti, int tlhNumThreads)
+{
+ int i, threadsFailed = 0;
+ const char *sep = "";
+
+ for (i = 0; i < tlhNumThreads; i++) {
+ if (ti[i].success != 0) {
+ threadsFailed = 1;
+ }
+ }
+ if (!threadsFailed) {
+ fprintf(stderr, "testLibHdfs: all threads succeeded. SUCCESS.\n");
+ return EXIT_SUCCESS;
+ }
+ fprintf(stderr, "testLibHdfs: some threads failed: [");
+ for (i = 0; i < tlhNumThreads; i++) {
+ if (ti[i].success != 0) {
+ fprintf(stderr, "%s%d", sep, i);
+ sep = ", ";
+ }
+ }
+ fprintf(stderr, "]. FAILURE.\n");
+ return EXIT_FAILURE;
+}
+
+/**
+ * Test that we can write a file with libhdfs and then read it back
+ */
+int main(void)
+{
+ int i, tlhNumThreads;
+ const char *tlhNumThreadsStr;
+ struct tlhThreadInfo ti[TLH_MAX_THREADS];
+ struct NativeMiniDfsConf conf = {
+ 1, /* doFormat */
+ };
+
+ tlhNumThreadsStr = getenv("TLH_NUM_THREADS");
+ if (!tlhNumThreadsStr) {
+ tlhNumThreadsStr = "3";
+ }
+ tlhNumThreads = atoi(tlhNumThreadsStr);
+ if ((tlhNumThreads <= 0) || (tlhNumThreads > TLH_MAX_THREADS)) {
+ fprintf(stderr, "testLibHdfs: must have a number of threads "
+ "between 1 and %d inclusive, not %d\n",
+ TLH_MAX_THREADS, tlhNumThreads);
+ return EXIT_FAILURE;
+ }
+ memset(&ti[0], 0, sizeof(ti));
+ for (i = 0; i < tlhNumThreads; i++) {
+ ti[i].threadIdx = i;
+ }
+
+ tlhCluster = nmdCreate(&conf);
+ EXPECT_NONNULL(tlhCluster);
+ EXPECT_ZERO(nmdWaitClusterUp(tlhCluster));
+
+ for (i = 0; i < tlhNumThreads; i++) {
+ ti[i].theThread.start = testHdfsOperations;
+ ti[i].theThread.arg = &ti[i];
+ EXPECT_ZERO(threadCreate(&ti[i].theThread));
+ }
+ for (i = 0; i < tlhNumThreads; i++) {
+ EXPECT_ZERO(threadJoin(&ti[i].theThread));
+ }
+
+ EXPECT_ZERO(nmdShutdown(tlhCluster));
+ nmdFree(tlhCluster);
+ return checkFailures(ti, tlhNumThreads);
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test_native_mini_dfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test_native_mini_dfs.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test_native_mini_dfs.c
new file mode 100644
index 0000000..850b0fc
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test_native_mini_dfs.c
@@ -0,0 +1,41 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "expect.h"
+#include "native_mini_dfs.h"
+
+#include <errno.h>
+
+static struct NativeMiniDfsConf conf = {
+ 1, /* doFormat */
+};
+
+/**
+ * Test that we can create a MiniDFSCluster and shut it down.
+ */
+int main(void) {
+ struct NativeMiniDfsCluster* cl;
+
+ cl = nmdCreate(&conf);
+ EXPECT_NONNULL(cl);
+ EXPECT_ZERO(nmdWaitClusterUp(cl));
+ EXPECT_ZERO(nmdShutdown(cl));
+ nmdFree(cl);
+
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 754ae7a..7ed40aa 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1483,6 +1483,8 @@ Release 2.8.0 - UNRELEASED
HDFS-9155. OEV should treat .XML files as XML even when the file name
extension is uppercase (nijel via cmccabe)
+ HDFS-9170. Move libhdfs / fuse-dfs / libwebhdfs to hdfs-client. (wheat9)
+
OPTIMIZATIONS
HDFS-8026. Trace FSOutputSummer#writeChecksumChunks rather than
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/pom.xml b/hadoop-hdfs-project/hadoop-hdfs/pom.xml
index ef3bcbd..9cea46a 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/pom.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs/pom.xml
@@ -34,8 +34,6 @@ http://maven.apache.org/xsd/maven-4.0.0.xsd">
<hadoop.component>hdfs</hadoop.component>
<kdc.resource.dir>../../hadoop-common-project/hadoop-common/src/test/resources/kdc</kdc.resource.dir>
<is.hadoop.component>true</is.hadoop.component>
- <require.fuse>false</require.fuse>
- <require.libwebhdfs>false</require.libwebhdfs>
</properties>
<dependencies>
@@ -421,173 +419,7 @@ http://maven.apache.org/xsd/maven-4.0.0.xsd">
</plugins>
</build>
- <profiles>
- <profile>
- <id>native-win</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- <os>
- <family>windows</family>
- </os>
- </activation>
- <properties>
- <runningWithNative>true</runningWithNative>
- </properties>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-enforcer-plugin</artifactId>
- <executions>
- <execution>
- <id>enforce-os</id>
- <goals>
- <goal>enforce</goal>
- </goals>
- <configuration>
- <rules>
- <requireOS>
- <family>windows</family>
- <message>native-win build only supported on Windows</message>
- </requireOS>
- </rules>
- <fail>true</fail>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <execution>
- <id>make</id>
- <phase>compile</phase>
- <goals>
- <goal>run</goal>
- </goals>
- <configuration>
- <target>
- <condition property="generator" value="Visual Studio 10" else="Visual Studio 10 Win64">
- <equals arg1="Win32" arg2="${env.PLATFORM}" />
- </condition>
- <mkdir dir="${project.build.directory}/native"/>
- <exec executable="cmake" dir="${project.build.directory}/native"
- failonerror="true">
- <arg line="${basedir}/src/ -DGENERATED_JAVAH=${project.build.directory}/native/javah -DJVM_ARCH_DATA_MODEL=${sun.arch.data.model} -DREQUIRE_LIBWEBHDFS=${require.libwebhdfs} -DREQUIRE_FUSE=${require.fuse} -G '${generator}'"/>
- </exec>
- <exec executable="msbuild" dir="${project.build.directory}/native"
- failonerror="true">
- <arg line="ALL_BUILD.vcxproj /nologo /p:Configuration=RelWithDebInfo /p:LinkIncremental=false"/>
- </exec>
- <!-- Copy for inclusion in distribution. -->
- <copy todir="${project.build.directory}/bin">
- <fileset dir="${project.build.directory}/native/target/bin/RelWithDebInfo"/>
- </copy>
- </target>
- </configuration>
- </execution>
- <execution>
- <id>native_tests</id>
- <phase>test</phase>
- <goals><goal>run</goal></goals>
- <configuration>
- <skip>${skipTests}</skip>
- <target>
- <property name="compile_classpath" refid="maven.compile.classpath"/>
- <property name="test_classpath" refid="maven.test.classpath"/>
- <macrodef name="run-test">
- <attribute name="test"/>
- <sequential>
- <echo message="Running @{test}"/>
- <exec executable="${project.build.directory}/native/RelWithDebInfo/@{test}" failonerror="true" dir="${project.build.directory}/native/">
- <env key="CLASSPATH" value="${test_classpath}:${compile_classpath}"/>
- <!-- HADOOP_HOME required to find winutils. -->
- <env key="HADOOP_HOME" value="${hadoop.common.build.dir}"/>
- <!-- Make sure hadoop.dll and jvm.dll are on PATH. -->
- <env key="PATH" value="${env.PATH};${hadoop.common.build.dir}/bin;${java.home}/jre/bin/server;${java.home}/bin/server"/>
- </exec>
- <echo message="Finished @{test}"/>
- </sequential>
- </macrodef>
- <run-test test="test_libhdfs_threaded"/>
- <echo message="Skipping test_libhdfs_zerocopy"/>
- <run-test test="test_native_mini_dfs"/>
- </target>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- <profile>
- <id>native</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
- <properties>
- <runningWithNative>true</runningWithNative>
- </properties>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <execution>
- <id>make</id>
- <phase>compile</phase>
- <goals><goal>run</goal></goals>
- <configuration>
- <target>
- <mkdir dir="${project.build.directory}/native"/>
- <exec executable="cmake" dir="${project.build.directory}/native"
- failonerror="true">
- <arg line="${basedir}/src/ -DGENERATED_JAVAH=${project.build.directory}/native/javah -DJVM_ARCH_DATA_MODEL=${sun.arch.data.model} -DREQUIRE_LIBWEBHDFS=${require.libwebhdfs} -DREQUIRE_FUSE=${require.fuse}"/>
- </exec>
- <exec executable="make" dir="${project.build.directory}/native" failonerror="true">
- <arg line="VERBOSE=1"/>
- </exec>
- <!-- The second make is a workaround for HADOOP-9215. It can
- be removed when version 2.6 of cmake is no longer supported . -->
- <exec executable="make" dir="${project.build.directory}/native" failonerror="true"></exec>
- </target>
- </configuration>
- </execution>
- <execution>
- <id>native_tests</id>
- <phase>test</phase>
- <goals><goal>run</goal></goals>
- <configuration>
- <skip>${skipTests}</skip>
- <target>
- <property name="compile_classpath" refid="maven.compile.classpath"/>
- <property name="test_classpath" refid="maven.test.classpath"/>
- <macrodef name="run-test">
- <attribute name="test"/>
- <sequential>
- <echo message="Running @{test}"/>
- <exec executable="${project.build.directory}/native/@{test}" failonerror="true" dir="${project.build.directory}/native/">
- <env key="CLASSPATH" value="${test_classpath}:${compile_classpath}"/>
- <!-- Make sure libhadoop.so is on LD_LIBRARY_PATH. -->
- <env key="LD_LIBRARY_PATH" value="${env.LD_LIBRARY_PATH}:${project.build.directory}/native/target/usr/local/lib:${hadoop.common.build.dir}/native/target/usr/local/lib"/>
- </exec>
- <echo message="Finished @{test}"/>
- </sequential>
- </macrodef>
- <run-test test="test_libhdfs_threaded"/>
- <run-test test="test_libhdfs_zerocopy"/>
- <run-test test="test_native_mini_dfs"/>
- </target>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
-
+ <profiles>
<!-- profile that starts ApacheDS KDC server -->
<profile>
<id>startKdc</id>
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/CMakeLists.txt b/hadoop-hdfs-project/hadoop-hdfs/src/CMakeLists.txt
deleted file mode 100644
index 2f8620b..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/CMakeLists.txt
+++ /dev/null
@@ -1,206 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-cmake_minimum_required(VERSION 2.6 FATAL_ERROR)
-
-list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/../../../hadoop-common-project/hadoop-common)
-include(HadoopCommon)
-
-#
-# Main configuration
-#
-
-# The caller must specify where the generated headers have been placed.
-if(NOT GENERATED_JAVAH)
- message(FATAL_ERROR "You must set the CMake variable GENERATED_JAVAH")
-endif()
-
-# Check to see if our compiler and linker support the __thread attribute.
-# On Linux and some other operating systems, this is a more efficient
-# alternative to POSIX thread local storage.
-include(CheckCSourceCompiles)
-check_c_source_compiles("int main(void) { static __thread int i = 0; return 0; }" HAVE_BETTER_TLS)
-
-# Check to see if we have Intel SSE intrinsics.
-check_c_source_compileS("#include <emmintrin.h>\nint main(void) { __m128d sum0 = _mm_set_pd(0.0,0.0); return 0; }" HAVE_INTEL_SSE_INTRINSICS)
-
-# Check if we need to link dl library to get dlopen.
-# dlopen on Linux is in separate library but on FreeBSD its in libc
-include(CheckLibraryExists)
-check_library_exists(dl dlopen "" NEED_LINK_DL)
-
-if(WIN32)
- # Set the optimizer level.
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /O2")
- # Set warning level 4.
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4")
- # Skip "unreferenced formal parameter".
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4100")
- # Skip "conditional expression is constant".
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4127")
- # Skip deprecated POSIX function warnings.
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_CRT_NONSTDC_NO_DEPRECATE")
- # Skip CRT non-secure function warnings. If we can convert usage of
- # strerror, getenv and ctime to their secure CRT equivalents, then we can
- # re-enable the CRT non-secure function warnings.
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_CRT_SECURE_NO_WARNINGS")
- # Omit unneeded headers.
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DWIN32_LEAN_AND_MEAN")
- set(OS_DIR main/native/libhdfs/os/windows)
- set(OUT_DIR target/bin)
-else()
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden")
- set(OS_DIR main/native/libhdfs/os/posix)
- set(OUT_DIR target/usr/local/lib)
-endif()
-
-# Configure JNI.
-include(HadoopJNI)
-
-add_definitions(-DLIBHDFS_DLL_EXPORT)
-
-include_directories(
- ${GENERATED_JAVAH}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_BINARY_DIR}
- ${JNI_INCLUDE_DIRS}
- main/native
- main/native/libhdfs
- ${OS_DIR}
-)
-
-set(_FUSE_DFS_VERSION 0.1.0)
-configure_file(${CMAKE_SOURCE_DIR}/config.h.cmake ${CMAKE_BINARY_DIR}/config.h)
-
-hadoop_add_dual_library(hdfs
- main/native/libhdfs/exception.c
- main/native/libhdfs/jni_helper.c
- main/native/libhdfs/hdfs.c
- main/native/libhdfs/common/htable.c
- ${OS_DIR}/mutexes.c
- ${OS_DIR}/thread_local_storage.c
-)
-if(NEED_LINK_DL)
- set(LIB_DL dl)
-endif()
-
-hadoop_target_link_dual_libraries(hdfs
- ${JAVA_JVM_LIBRARY}
- ${LIB_DL}
- ${OS_LINK_LIBRARIES}
-)
-
-hadoop_dual_output_directory(hdfs ${OUT_DIR})
-set(LIBHDFS_VERSION "0.0.0")
-set_target_properties(hdfs PROPERTIES
- SOVERSION ${LIBHDFS_VERSION})
-
-add_executable(test_libhdfs_ops
- main/native/libhdfs/test/test_libhdfs_ops.c
-)
-target_link_libraries(test_libhdfs_ops
- hdfs_static
- ${JAVA_JVM_LIBRARY}
-)
-
-add_executable(test_libhdfs_read
- main/native/libhdfs/test/test_libhdfs_read.c
-)
-target_link_libraries(test_libhdfs_read
- hdfs_static
- ${JAVA_JVM_LIBRARY}
-)
-
-add_executable(test_libhdfs_write
- main/native/libhdfs/test/test_libhdfs_write.c
-)
-target_link_libraries(test_libhdfs_write
- hdfs_static
- ${JAVA_JVM_LIBRARY}
-)
-
-add_library(native_mini_dfs
- main/native/libhdfs/native_mini_dfs.c
- main/native/libhdfs/common/htable.c
- main/native/libhdfs/exception.c
- main/native/libhdfs/jni_helper.c
- ${OS_DIR}/mutexes.c
- ${OS_DIR}/thread_local_storage.c
-)
-target_link_libraries(native_mini_dfs
- ${JAVA_JVM_LIBRARY}
- ${LIB_DL}
- ${OS_LINK_LIBRARIES}
-)
-
-add_executable(test_native_mini_dfs
- main/native/libhdfs/test_native_mini_dfs.c
-)
-target_link_libraries(test_native_mini_dfs
- native_mini_dfs
-)
-
-add_executable(test_libhdfs_threaded
- main/native/libhdfs/expect.c
- main/native/libhdfs/test_libhdfs_threaded.c
- ${OS_DIR}/thread.c
-)
-target_link_libraries(test_libhdfs_threaded
- hdfs_static
- native_mini_dfs
- ${OS_LINK_LIBRARIES}
-)
-
-add_executable(test_libhdfs_zerocopy
- main/native/libhdfs/expect.c
- main/native/libhdfs/test/test_libhdfs_zerocopy.c
-)
-target_link_libraries(test_libhdfs_zerocopy
- hdfs_static
- native_mini_dfs
- ${OS_LINK_LIBRARIES}
-)
-
-add_executable(test_htable
- main/native/libhdfs/common/htable.c
- main/native/libhdfs/test/test_htable.c
-)
-target_link_libraries(test_htable
- ${OS_LINK_LIBRARIES}
-)
-
-# Skip vecsum on Windows. This could be made to work in the future by
-# introducing an abstraction layer over the sys/mman.h functions.
-if(NOT WIN32)
- add_executable(test_libhdfs_vecsum main/native/libhdfs/test/vecsum.c)
- if(CMAKE_SYSTEM_NAME MATCHES "Darwin")
- target_link_libraries(test_libhdfs_vecsum
- hdfs
- pthread)
- else()
- target_link_libraries(test_libhdfs_vecsum
- hdfs
- pthread
- rt)
- endif()
-endif()
-
-if(REQUIRE_LIBWEBHDFS)
- add_subdirectory(contrib/libwebhdfs)
-endif()
-add_subdirectory(main/native/fuse-dfs)
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/config.h.cmake
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/config.h.cmake b/hadoop-hdfs-project/hadoop-hdfs/src/config.h.cmake
deleted file mode 100644
index 0d11fc4..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/config.h.cmake
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you 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.
-*/
-#ifndef CONFIG_H
-#define CONFIG_H
-
-#cmakedefine _FUSE_DFS_VERSION "@_FUSE_DFS_VERSION@"
-
-#cmakedefine HAVE_BETTER_TLS
-
-#cmakedefine HAVE_INTEL_SSE_INTRINSICS
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/CMakeLists.txt b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/CMakeLists.txt
deleted file mode 100644
index dc74feb..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/CMakeLists.txt
+++ /dev/null
@@ -1,78 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-find_package(CURL REQUIRED)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
- "${CMAKE_SOURCE_DIR}/contrib/libwebhdfs/resources/")
-
-find_package(Jansson REQUIRED)
-include_directories(${JANSSON_INCLUDE_DIR})
-
-hadoop_add_dual_library(webhdfs
- src/hdfs_web.c
- src/hdfs_http_client.c
- src/hdfs_http_query.c
- src/hdfs_json_parser.c
- ../../main/native/libhdfs/exception.c
- ../../main/native/libhdfs/jni_helper.c
- ../../${OS_DIR}/mutexes.c
- ../../${OS_DIR}/thread_local_storage.c
- ../../main/native/libhdfs/common/htable.c
-)
-hadoop_target_link_dual_libraries(webhdfs
- ${JAVA_JVM_LIBRARY}
- ${CURL_LIBRARY}
- ${JANSSON_LIBRARY}
- pthread
-)
-hadoop_dual_output_directory(webhdfs target)
-set(LIBWEBHDFS_VERSION "0.0.0")
-set_target_properties(webhdfs PROPERTIES
- SOVERSION ${LIBWEBHDFS_VERSION})
-
-add_executable(test_libwebhdfs_ops
- src/test_libwebhdfs_ops.c
-)
-target_link_libraries(test_libwebhdfs_ops
- webhdfs
- native_mini_dfs
-)
-
-add_executable(test_libwebhdfs_read
- src/test_libwebhdfs_read.c
-)
-target_link_libraries(test_libwebhdfs_read
- webhdfs
-)
-
-add_executable(test_libwebhdfs_write
- src/test_libwebhdfs_write.c
-)
-target_link_libraries(test_libwebhdfs_write
- webhdfs
-)
-
-add_executable(test_libwebhdfs_threaded
- src/test_libwebhdfs_threaded.c
-)
-target_link_libraries(test_libwebhdfs_threaded
- webhdfs
- native_mini_dfs
- pthread
-)
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/resources/FindJansson.cmake
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/resources/FindJansson.cmake b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/resources/FindJansson.cmake
deleted file mode 100644
index b8c67ea..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/resources/FindJansson.cmake
+++ /dev/null
@@ -1,43 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-
-
-# - Try to find Jansson
-# Once done this will define
-# JANSSON_FOUND - System has Jansson
-# JANSSON_INCLUDE_DIRS - The Jansson include directories
-# JANSSON_LIBRARIES - The libraries needed to use Jansson
-# JANSSON_DEFINITIONS - Compiler switches required for using Jansson
-
-find_path(JANSSON_INCLUDE_DIR jansson.h
- /usr/include
- /usr/include/jansson
- /usr/local/include )
-
-find_library(JANSSON_LIBRARY NAMES jansson
- PATHS /usr/lib /usr/local/lib )
-
-set(JANSSON_LIBRARIES ${JANSSON_LIBRARY} )
-set(JANSSON_INCLUDE_DIRS ${JANSSON_INCLUDE_DIR} )
-
-include(FindPackageHandleStandardArgs)
-# handle the QUIETLY and REQUIRED arguments and set JANSSON_FOUND to TRUE
-# if all listed variables are TRUE
-find_package_handle_standard_args(Jansson DEFAULT_MSG
- JANSSON_LIBRARY JANSSON_INCLUDE_DIR)
-
-mark_as_advanced(JANSSON_INCLUDE_DIR JANSSON_LIBRARY )
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_client.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_client.c b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_client.c
deleted file mode 100644
index dc5ca41..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_client.c
+++ /dev/null
@@ -1,490 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include <stdlib.h>
-#include <string.h>
-#include <curl/curl.h>
-
-#include "hdfs_http_client.h"
-#include "exception.h"
-
-static pthread_mutex_t curlInitMutex = PTHREAD_MUTEX_INITIALIZER;
-static volatile int curlGlobalInited = 0;
-
-const char *hdfs_strerror(int errnoval)
-{
-#if defined(__sun)
-// MT-Safe under Solaris which doesn't support sys_errlist/sys_nerr
- return strerror(errnoval);
-#else
- if ((errnoval < 0) || (errnoval >= sys_nerr)) {
- return "unknown error.";
- }
- return sys_errlist[errnoval];
-#endif
-}
-
-int initResponseBuffer(struct ResponseBuffer **buffer)
-{
- struct ResponseBuffer *info = NULL;
- int ret = 0;
- info = calloc(1, sizeof(struct ResponseBuffer));
- if (!info) {
- ret = ENOMEM;
- }
- *buffer = info;
- return ret;
-}
-
-void freeResponseBuffer(struct ResponseBuffer *buffer)
-{
- if (buffer) {
- if (buffer->content) {
- free(buffer->content);
- }
- free(buffer);
- buffer = NULL;
- }
-}
-
-void freeResponse(struct Response *resp)
-{
- if (resp) {
- freeResponseBuffer(resp->body);
- freeResponseBuffer(resp->header);
- free(resp);
- resp = NULL;
- }
-}
-
-/**
- * Callback used by libcurl for allocating local buffer and
- * reading data to local buffer
- */
-static size_t writefunc(void *ptr, size_t size,
- size_t nmemb, struct ResponseBuffer *rbuffer)
-{
- void *temp = NULL;
- if (size * nmemb < 1) {
- return 0;
- }
- if (!rbuffer) {
- fprintf(stderr,
- "ERROR: ResponseBuffer is NULL for the callback writefunc.\n");
- return 0;
- }
-
- if (rbuffer->remaining < size * nmemb) {
- temp = realloc(rbuffer->content, rbuffer->offset + size * nmemb + 1);
- if (temp == NULL) {
- fprintf(stderr, "ERROR: fail to realloc in callback writefunc.\n");
- return 0;
- }
- rbuffer->content = temp;
- rbuffer->remaining = size * nmemb;
- }
- memcpy(rbuffer->content + rbuffer->offset, ptr, size * nmemb);
- rbuffer->offset += size * nmemb;
- (rbuffer->content)[rbuffer->offset] = '\0';
- rbuffer->remaining -= size * nmemb;
- return size * nmemb;
-}
-
-/**
- * Callback used by libcurl for reading data into buffer provided by user,
- * thus no need to reallocate buffer.
- */
-static size_t writeFuncWithUserBuffer(void *ptr, size_t size,
- size_t nmemb, struct ResponseBuffer *rbuffer)
-{
- size_t toCopy = 0;
- if (size * nmemb < 1) {
- return 0;
- }
- if (!rbuffer || !rbuffer->content) {
- fprintf(stderr,
- "ERROR: buffer to read is NULL for the "
- "callback writeFuncWithUserBuffer.\n");
- return 0;
- }
-
- toCopy = rbuffer->remaining < (size * nmemb) ?
- rbuffer->remaining : (size * nmemb);
- memcpy(rbuffer->content + rbuffer->offset, ptr, toCopy);
- rbuffer->offset += toCopy;
- rbuffer->remaining -= toCopy;
- return toCopy;
-}
-
-/**
- * Callback used by libcurl for writing data to remote peer
- */
-static size_t readfunc(void *ptr, size_t size, size_t nmemb, void *stream)
-{
- struct webhdfsBuffer *wbuffer = NULL;
- if (size * nmemb < 1) {
- return 0;
- }
-
- wbuffer = stream;
- pthread_mutex_lock(&wbuffer->writeMutex);
- while (wbuffer->remaining == 0) {
- /*
- * The current remainning bytes to write is 0,
- * check closeFlag to see whether need to finish the transfer.
- * if yes, return 0; else, wait
- */
- if (wbuffer->closeFlag) { // We can close the transfer now
- //For debug
- fprintf(stderr, "CloseFlag is set, ready to close the transfer\n");
- pthread_mutex_unlock(&wbuffer->writeMutex);
- return 0;
- } else {
- // remaining == 0 but closeFlag is not set
- // indicates that user's buffer has been transferred
- pthread_cond_signal(&wbuffer->transfer_finish);
- pthread_cond_wait(&wbuffer->newwrite_or_close,
- &wbuffer->writeMutex);
- }
- }
-
- if (wbuffer->remaining > 0 && !wbuffer->closeFlag) {
- size_t copySize = wbuffer->remaining < size * nmemb ?
- wbuffer->remaining : size * nmemb;
- memcpy(ptr, wbuffer->wbuffer + wbuffer->offset, copySize);
- wbuffer->offset += copySize;
- wbuffer->remaining -= copySize;
- pthread_mutex_unlock(&wbuffer->writeMutex);
- return copySize;
- } else {
- fprintf(stderr, "ERROR: webhdfsBuffer's remaining is %ld, "
- "it should be a positive value!\n", wbuffer->remaining);
- pthread_mutex_unlock(&wbuffer->writeMutex);
- return 0;
- }
-}
-
-/**
- * Initialize the global libcurl environment
- */
-static void initCurlGlobal()
-{
- if (!curlGlobalInited) {
- pthread_mutex_lock(&curlInitMutex);
- if (!curlGlobalInited) {
- curl_global_init(CURL_GLOBAL_ALL);
- curlGlobalInited = 1;
- }
- pthread_mutex_unlock(&curlInitMutex);
- }
-}
-
-/**
- * Launch simple commands (commands without file I/O) and return response
- *
- * @param url Target URL
- * @param method HTTP method (GET/PUT/POST)
- * @param followloc Whether or not need to set CURLOPT_FOLLOWLOCATION
- * @param response Response from remote service
- * @return 0 for success and non-zero value to indicate error
- */
-static int launchCmd(const char *url, enum HttpHeader method,
- enum Redirect followloc, struct Response **response)
-{
- CURL *curl = NULL;
- CURLcode curlCode;
- int ret = 0;
- struct Response *resp = NULL;
-
- resp = calloc(1, sizeof(struct Response));
- if (!resp) {
- return ENOMEM;
- }
- ret = initResponseBuffer(&(resp->body));
- if (ret) {
- goto done;
- }
- ret = initResponseBuffer(&(resp->header));
- if (ret) {
- goto done;
- }
- initCurlGlobal();
- curl = curl_easy_init();
- if (!curl) {
- ret = ENOMEM; // curl_easy_init does not return error code,
- // and most of its errors are caused by malloc()
- fprintf(stderr, "ERROR in curl_easy_init.\n");
- goto done;
- }
- /* Set callback function for reading data from remote service */
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp->body);
- curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writefunc);
- curl_easy_setopt(curl, CURLOPT_WRITEHEADER, resp->header);
- curl_easy_setopt(curl, CURLOPT_URL, url);
- switch(method) {
- case GET:
- break;
- case PUT:
- curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
- break;
- case POST:
- curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
- break;
- case DELETE:
- curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
- break;
- default:
- ret = EINVAL;
- fprintf(stderr, "ERROR: Invalid HTTP method\n");
- goto done;
- }
- if (followloc == YES) {
- curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
- }
- /* Now run the curl handler */
- curlCode = curl_easy_perform(curl);
- if (curlCode != CURLE_OK) {
- ret = EIO;
- fprintf(stderr, "ERROR: preform the URL %s failed, <%d>: %s\n",
- url, curlCode, curl_easy_strerror(curlCode));
- }
-done:
- if (curl != NULL) {
- curl_easy_cleanup(curl);
- }
- if (ret) {
- free(resp);
- resp = NULL;
- }
- *response = resp;
- return ret;
-}
-
-/**
- * Launch the read request. The request is sent to the NameNode and then
- * redirected to corresponding DataNode
- *
- * @param url The URL for the read request
- * @param resp The response containing the buffer provided by user
- * @return 0 for success and non-zero value to indicate error
- */
-static int launchReadInternal(const char *url, struct Response* resp)
-{
- CURL *curl;
- CURLcode curlCode;
- int ret = 0;
-
- if (!resp || !resp->body || !resp->body->content) {
- fprintf(stderr,
- "ERROR: invalid user-provided buffer!\n");
- return EINVAL;
- }
-
- initCurlGlobal();
- /* get a curl handle */
- curl = curl_easy_init();
- if (!curl) {
- fprintf(stderr, "ERROR in curl_easy_init.\n");
- return ENOMEM;
- }
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFuncWithUserBuffer);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp->body);
- curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writefunc);
- curl_easy_setopt(curl, CURLOPT_WRITEHEADER, resp->header);
- curl_easy_setopt(curl, CURLOPT_URL, url);
- curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
-
- curlCode = curl_easy_perform(curl);
- if (curlCode != CURLE_OK && curlCode != CURLE_PARTIAL_FILE) {
- ret = EIO;
- fprintf(stderr, "ERROR: preform the URL %s failed, <%d>: %s\n",
- url, curlCode, curl_easy_strerror(curlCode));
- }
-
- curl_easy_cleanup(curl);
- return ret;
-}
-
-/**
- * The function does the write operation by connecting to a DataNode.
- * The function keeps the connection with the DataNode until
- * the closeFlag is set. Whenever the current data has been sent out,
- * the function blocks waiting for further input from user or close.
- *
- * @param url URL of the remote DataNode
- * @param method PUT for create and POST for append
- * @param uploadBuffer Buffer storing user's data to write
- * @param response Response from remote service
- * @return 0 for success and non-zero value to indicate error
- */
-static int launchWrite(const char *url, enum HttpHeader method,
- struct webhdfsBuffer *uploadBuffer,
- struct Response **response)
-{
- CURLcode curlCode;
- struct Response* resp = NULL;
- struct curl_slist *chunk = NULL;
- CURL *curl = NULL;
- int ret = 0;
-
- if (!uploadBuffer) {
- fprintf(stderr, "ERROR: upload buffer is NULL!\n");
- return EINVAL;
- }
-
- initCurlGlobal();
- resp = calloc(1, sizeof(struct Response));
- if (!resp) {
- return ENOMEM;
- }
- ret = initResponseBuffer(&(resp->body));
- if (ret) {
- goto done;
- }
- ret = initResponseBuffer(&(resp->header));
- if (ret) {
- goto done;
- }
-
- // Connect to the datanode in order to create the lease in the namenode
- curl = curl_easy_init();
- if (!curl) {
- fprintf(stderr, "ERROR: failed to initialize the curl handle.\n");
- return ENOMEM;
- }
- curl_easy_setopt(curl, CURLOPT_URL, url);
-
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp->body);
- curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writefunc);
- curl_easy_setopt(curl, CURLOPT_WRITEHEADER, resp->header);
- curl_easy_setopt(curl, CURLOPT_READFUNCTION, readfunc);
- curl_easy_setopt(curl, CURLOPT_READDATA, uploadBuffer);
- curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
-
- chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked");
- curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
- chunk = curl_slist_append(chunk, "Expect:");
- curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
-
- switch(method) {
- case PUT:
- curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
- break;
- case POST:
- curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
- break;
- default:
- ret = EINVAL;
- fprintf(stderr, "ERROR: Invalid HTTP method\n");
- goto done;
- }
- curlCode = curl_easy_perform(curl);
- if (curlCode != CURLE_OK) {
- ret = EIO;
- fprintf(stderr, "ERROR: preform the URL %s failed, <%d>: %s\n",
- url, curlCode, curl_easy_strerror(curlCode));
- }
-
-done:
- if (chunk != NULL) {
- curl_slist_free_all(chunk);
- }
- if (curl != NULL) {
- curl_easy_cleanup(curl);
- }
- if (ret) {
- free(resp);
- resp = NULL;
- }
- *response = resp;
- return ret;
-}
-
-int launchMKDIR(const char *url, struct Response **resp)
-{
- return launchCmd(url, PUT, NO, resp);
-}
-
-int launchRENAME(const char *url, struct Response **resp)
-{
- return launchCmd(url, PUT, NO, resp);
-}
-
-int launchGFS(const char *url, struct Response **resp)
-{
- return launchCmd(url, GET, NO, resp);
-}
-
-int launchLS(const char *url, struct Response **resp)
-{
- return launchCmd(url, GET, NO, resp);
-}
-
-int launchCHMOD(const char *url, struct Response **resp)
-{
- return launchCmd(url, PUT, NO, resp);
-}
-
-int launchCHOWN(const char *url, struct Response **resp)
-{
- return launchCmd(url, PUT, NO, resp);
-}
-
-int launchDELETE(const char *url, struct Response **resp)
-{
- return launchCmd(url, DELETE, NO, resp);
-}
-
-int launchOPEN(const char *url, struct Response* resp)
-{
- return launchReadInternal(url, resp);
-}
-
-int launchUTIMES(const char *url, struct Response **resp)
-{
- return launchCmd(url, PUT, NO, resp);
-}
-
-int launchNnWRITE(const char *url, struct Response **resp)
-{
- return launchCmd(url, PUT, NO, resp);
-}
-
-int launchNnAPPEND(const char *url, struct Response **resp)
-{
- return launchCmd(url, POST, NO, resp);
-}
-
-int launchDnWRITE(const char *url, struct webhdfsBuffer *buffer,
- struct Response **resp)
-{
- return launchWrite(url, PUT, buffer, resp);
-}
-
-int launchDnAPPEND(const char *url, struct webhdfsBuffer *buffer,
- struct Response **resp)
-{
- return launchWrite(url, POST, buffer, resp);
-}
-
-int launchSETREPLICATION(const char *url, struct Response **resp)
-{
- return launchCmd(url, PUT, NO, resp);
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_client.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_client.h b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_client.h
deleted file mode 100644
index 8d1c3db..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_client.h
+++ /dev/null
@@ -1,294 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-
-
-#ifndef _HDFS_HTTP_CLIENT_H_
-#define _HDFS_HTTP_CLIENT_H_
-
-#include "hdfs.h" /* for tSize */
-
-#include <pthread.h> /* for pthread_t */
-#include <unistd.h> /* for size_t */
-
-/** enum indicating the type of hdfs stream */
-enum hdfsStreamType
-{
- UNINITIALIZED = 0,
- INPUT = 1,
- OUTPUT = 2,
-};
-
-/**
- * webhdfsBuffer - used for hold the data for read/write from/to http connection
- */
-struct webhdfsBuffer {
- const char *wbuffer; /* The user's buffer for uploading */
- size_t remaining; /* Length of content */
- size_t offset; /* offset for reading */
- /* Check whether the hdfsOpenFile has been called before */
- int openFlag;
- /* Whether to close the http connection for writing */
- int closeFlag;
- /* Synchronization between the curl and hdfsWrite threads */
- pthread_mutex_t writeMutex;
- /*
- * Transferring thread waits for this condition
- * when there is no more content for transferring in the buffer
- */
- pthread_cond_t newwrite_or_close;
- /* Condition used to indicate finishing transferring (one buffer) */
- pthread_cond_t transfer_finish;
-};
-
-/** File handle for webhdfs */
-struct webhdfsFileHandle {
- char *absPath; /* Absolute path of file */
- int bufferSize; /* Size of buffer */
- short replication; /* Number of replication */
- tSize blockSize; /* Block size */
- char *datanode; /* URL of the DataNode */
- /* webhdfsBuffer handle used to store the upload data */
- struct webhdfsBuffer *uploadBuffer;
- /* The thread used for data transferring */
- pthread_t connThread;
-};
-
-/** Type of http header */
-enum HttpHeader {
- GET,
- PUT,
- POST,
- DELETE
-};
-
-/** Whether to redirect */
-enum Redirect {
- YES,
- NO
-};
-
-/** Buffer used for holding response */
-struct ResponseBuffer {
- char *content;
- size_t remaining;
- size_t offset;
-};
-
-/**
- * The response got through webhdfs
- */
-struct Response {
- struct ResponseBuffer *body;
- struct ResponseBuffer *header;
-};
-
-/**
- * Create and initialize a ResponseBuffer
- *
- * @param buffer Pointer pointing to new created ResponseBuffer handle
- * @return 0 for success, non-zero value to indicate error
- */
-int initResponseBuffer(struct ResponseBuffer **buffer) __attribute__ ((warn_unused_result));
-
-/**
- * Free the given ResponseBuffer
- *
- * @param buffer The ResponseBuffer to free
- */
-void freeResponseBuffer(struct ResponseBuffer *buffer);
-
-/**
- * Free the given Response
- *
- * @param resp The Response to free
- */
-void freeResponse(struct Response *resp);
-
-/**
- * Send the MKDIR request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for MKDIR operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchMKDIR(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the RENAME request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for RENAME operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchRENAME(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the CHMOD request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for CHMOD operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchCHMOD(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the GetFileStatus request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for GetFileStatus operation
- * @param response Response handle to store response returned from the NameNode,
- * containing either file status or exception information
- * @return 0 for success, non-zero value to indicate error
- */
-int launchGFS(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the LS (LISTSTATUS) request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for LISTSTATUS operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchLS(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the DELETE request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for DELETE operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchDELETE(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the CHOWN request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for CHOWN operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchCHOWN(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the OPEN request to NameNode using the given URL,
- * asking for reading a file (within a range).
- * The NameNode first redirects the request to the datanode
- * that holds the corresponding first block of the file (within a range),
- * and the datanode returns the content of the file through the HTTP connection.
- *
- * @param url The URL for OPEN operation
- * @param resp The response holding user's buffer.
- The file content will be written into the buffer.
- * @return 0 for success, non-zero value to indicate error
- */
-int launchOPEN(const char *url,
- struct Response* resp) __attribute__ ((warn_unused_result));
-
-/**
- * Send the SETTIMES request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for SETTIMES operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchUTIMES(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the WRITE/CREATE request to NameNode using the given URL.
- * The NameNode will choose the writing target datanodes
- * and return the first datanode in the pipeline as response
- *
- * @param url The URL for WRITE/CREATE operation connecting to NameNode
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchNnWRITE(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the WRITE request along with to-write content to
- * the corresponding DataNode using the given URL.
- * The DataNode will write the data and return the response.
- *
- * @param url The URL for WRITE operation connecting to DataNode
- * @param buffer The webhdfsBuffer containing data to be written to hdfs
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchDnWRITE(const char *url, struct webhdfsBuffer *buffer,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the WRITE (APPEND) request to NameNode using the given URL.
- * The NameNode determines the DataNode for appending and
- * sends its URL back as response.
- *
- * @param url The URL for APPEND operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchNnAPPEND(const char *url, struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the SETREPLICATION request to NameNode using the given URL.
- * The NameNode will execute the operation and return the result as response.
- *
- * @param url The URL for SETREPLICATION operation
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchSETREPLICATION(const char *url,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Send the APPEND request along with the content to DataNode.
- * The DataNode will do the appending and return the result as response.
- *
- * @param url The URL for APPEND operation connecting to DataNode
- * @param buffer The webhdfsBuffer containing data to be appended
- * @param response Response handle to store response returned from the NameNode
- * @return 0 for success, non-zero value to indicate error
- */
-int launchDnAPPEND(const char *url, struct webhdfsBuffer *buffer,
- struct Response **response) __attribute__ ((warn_unused_result));
-
-/**
- * Thread-safe strerror alternative.
- *
- * @param errnoval The error code value
- * @return The error message string mapped to the given error code
- */
-const char *hdfs_strerror(int errnoval);
-
-#endif //_HDFS_HTTP_CLIENT_H_
[03/35] hadoop git commit: HDFS-9182. Cleanup the findbugs and other
issues after HDFS EC merged to trunk. Contributed by Uma Maheswara Rao G.
Posted by ji...@apache.org.
HDFS-9182. Cleanup the findbugs and other issues after HDFS EC merged to trunk. Contributed by Uma Maheswara Rao G.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/8b733931
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/8b733931
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/8b733931
Branch: refs/heads/HDFS-8966
Commit: 8b7339312cb06b7e021f8f9ea6e3a20ebf009af3
Parents: 3793cbe
Author: Uma Mahesh <um...@apache.org>
Authored: Tue Oct 6 22:22:32 2015 -0700
Committer: Uma Mahesh <um...@apache.org>
Committed: Tue Oct 6 22:22:32 2015 -0700
----------------------------------------------------------------------
.../hadoop-common/CHANGES-HDFS-EC-7285.txt | 74 ---
hadoop-common-project/hadoop-common/CHANGES.txt | 75 +++
.../dev-support/findbugsExcludeFile.xml | 3 +
.../org/apache/hadoop/hdfs/DFSOutputStream.java | 2 +-
.../hadoop/hdfs/DFSStripedOutputStream.java | 2 +-
.../hadoop-hdfs/CHANGES-HDFS-EC-7285.txt | 460 ------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 464 +++++++++++++++++++
7 files changed, 544 insertions(+), 536 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8b733931/hadoop-common-project/hadoop-common/CHANGES-HDFS-EC-7285.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES-HDFS-EC-7285.txt b/hadoop-common-project/hadoop-common/CHANGES-HDFS-EC-7285.txt
deleted file mode 100644
index 1f3006e..0000000
--- a/hadoop-common-project/hadoop-common/CHANGES-HDFS-EC-7285.txt
+++ /dev/null
@@ -1,74 +0,0 @@
- BREAKDOWN OF HADOOP-11264 SUBTASKS AND RELATED JIRAS (Common part of HDFS-7285)
-
- HADOOP-11514. Raw Erasure Coder API for concrete encoding and decoding
- (Kai Zheng via umamahesh)
-
- HADOOP-11534. Minor improvements for raw erasure coders
- ( Kai Zheng via vinayakumarb )
-
- HADOOP-11541. Raw XOR coder
- ( Kai Zheng )
-
- HADOOP-11542. Raw Reed-Solomon coder in pure Java. Contributed by Kai Zheng
- ( Kai Zheng )
-
- HADOOP-11643. Define EC schema API for ErasureCodec. Contributed by Kai Zheng
- ( Kai Zheng )
-
- HADOOP-11646. Erasure Coder API for encoding and decoding of block group
- ( Kai Zheng via vinayakumarb )
-
- HADOOP-11705. Make erasure coder configurable. Contributed by Kai Zheng
- ( Kai Zheng )
-
- HADOOP-11706. Refine a little bit erasure coder API. Contributed by Kai Zheng
- ( Kai Zheng )
-
- HADOOP-11707. Add factory to create raw erasure coder. Contributed by Kai Zheng
- ( Kai Zheng )
-
- HADOOP-11647. Reed-Solomon ErasureCoder. Contributed by Kai Zheng
- ( Kai Zheng )
-
- HADOOP-11782 Correct two thrown messages in ECSchema class. Contributed by Xinwei Qin
- ( Xinwei Qin via Kai Zheng )
-
- HADOOP-11740. Combine erasure encoder and decoder interfaces (Zhe Zhang)
-
- HADOOP-11805 Better to rename some raw erasure coders. Contributed by Kai Zheng
- ( Kai Zheng )
-
- HADOOP-11645. Erasure Codec API covering the essential aspects for an erasure code
- ( Kai Zheng via vinayakumarb )
-
- HADOOP-11818. Minor improvements for erasurecode classes. (Rakesh R via Kai Zheng)
-
- HADOOP-11841. Remove unused ecschema-def.xml files. (szetszwo)
-
- HADOOP-11921. Enhance tests for erasure coders. (Kai Zheng via Zhe Zhang)
-
- HADOOP-11920. Refactor some codes for erasure coders. (Kai Zheng via Zhe Zhang)
-
- HADOOP-11566. Add tests and fix for erasure coders to recover erased parity
- units. (Kai Zheng via Zhe Zhang)
-
- HADOOP-11938. Enhance ByteBuffer version encode/decode API of raw erasure
- coder. (Kai Zheng via Zhe Zhang)
-
- HADOOP-12013. Generate fixed data to perform erasure coder test. (Kai Zheng)
-
- HADOOP-12029. Remove chunkSize from ECSchema as its not required for coders
- (vinayakumarb)
-
- HADOOP-11847. Enhance raw coder allowing to read least required inputs in decoding.
- (Kai Zheng)
-
- HADOOP-12011. Allow to dump verbose information to ease debugging in raw erasure coders
- (Kai Zheng)
-
- HADOOP-12065. Using more meaningful keys in EC schema. (Kai Zheng)
-
- HDFS-8557. Allow to configure RS and XOR raw coders (Kai Zheng)
-
- HADOOP-12060. Fix ByteBuffer usage for raw erasure coders. (Kai Zheng via
- jing9)
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8b733931/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index f92d720..fd6e2f1 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -513,6 +513,81 @@ Trunk (Unreleased)
HADOOP-8589. ViewFs tests fail when tests and home dirs are nested (sanjay Radia)
+ BREAKDOWN OF HADOOP-11264 SUBTASKS AND RELATED JIRAS (Common part of HDFS-7285)
+
+ HADOOP-11514. Raw Erasure Coder API for concrete encoding and decoding
+ (Kai Zheng via umamahesh)
+
+ HADOOP-11534. Minor improvements for raw erasure coders
+ ( Kai Zheng via vinayakumarb )
+
+ HADOOP-11541. Raw XOR coder
+ ( Kai Zheng )
+
+ HADOOP-11542. Raw Reed-Solomon coder in pure Java. Contributed by Kai Zheng
+ ( Kai Zheng )
+
+ HADOOP-11643. Define EC schema API for ErasureCodec. Contributed by Kai Zheng
+ ( Kai Zheng )
+
+ HADOOP-11646. Erasure Coder API for encoding and decoding of block group
+ ( Kai Zheng via vinayakumarb )
+
+ HADOOP-11705. Make erasure coder configurable. Contributed by Kai Zheng
+ ( Kai Zheng )
+
+ HADOOP-11706. Refine a little bit erasure coder API. Contributed by Kai Zheng
+ ( Kai Zheng )
+
+ HADOOP-11707. Add factory to create raw erasure coder. Contributed by Kai Zheng
+ ( Kai Zheng )
+
+ HADOOP-11647. Reed-Solomon ErasureCoder. Contributed by Kai Zheng
+ ( Kai Zheng )
+
+ HADOOP-11782 Correct two thrown messages in ECSchema class. Contributed by Xinwei Qin
+ ( Xinwei Qin via Kai Zheng )
+
+ HADOOP-11740. Combine erasure encoder and decoder interfaces (Zhe Zhang)
+
+ HADOOP-11805 Better to rename some raw erasure coders. Contributed by Kai Zheng
+ ( Kai Zheng )
+
+ HADOOP-11645. Erasure Codec API covering the essential aspects for an erasure code
+ ( Kai Zheng via vinayakumarb )
+
+ HADOOP-11818. Minor improvements for erasurecode classes. (Rakesh R via Kai Zheng)
+
+ HADOOP-11841. Remove unused ecschema-def.xml files. (szetszwo)
+
+ HADOOP-11921. Enhance tests for erasure coders. (Kai Zheng via Zhe Zhang)
+
+ HADOOP-11920. Refactor some codes for erasure coders. (Kai Zheng via Zhe Zhang)
+
+ HADOOP-11566. Add tests and fix for erasure coders to recover erased parity
+ units. (Kai Zheng via Zhe Zhang)
+
+ HADOOP-11938. Enhance ByteBuffer version encode/decode API of raw erasure
+ coder. (Kai Zheng via Zhe Zhang)
+
+ HADOOP-12013. Generate fixed data to perform erasure coder test. (Kai Zheng)
+
+ HADOOP-12029. Remove chunkSize from ECSchema as its not required for coders
+ (vinayakumarb)
+
+ HADOOP-11847. Enhance raw coder allowing to read least required inputs in decoding.
+ (Kai Zheng)
+
+ HADOOP-12011. Allow to dump verbose information to ease debugging in raw erasure coders
+ (Kai Zheng)
+
+ HADOOP-12065. Using more meaningful keys in EC schema. (Kai Zheng)
+
+ HADOOP-12060. Fix ByteBuffer usage for raw erasure coders. (Kai Zheng via
+ jing9)
+
+ HADOOP-11921. Enhance tests for erasure coders. (Kai Zheng)
+
Release 2.8.0 - UNRELEASED
INCOMPATIBLE CHANGES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8b733931/hadoop-hdfs-project/hadoop-hdfs-client/dev-support/findbugsExcludeFile.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/dev-support/findbugsExcludeFile.xml b/hadoop-hdfs-project/hadoop-hdfs-client/dev-support/findbugsExcludeFile.xml
index 41a8564..14e4d5d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/dev-support/findbugsExcludeFile.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/dev-support/findbugsExcludeFile.xml
@@ -15,6 +15,9 @@
<Class name="org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus"/>
<Class name="org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport"/>
<Class name="org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslResponseWithNegotiatedCipherOption"/>
+ <Class name="org.apache.hadoop.hdfs.DFSPacket”/>
+ <Class name="org.apache.hadoop.hdfs.protocol.LocatedStripedBlock”/>
+ <Class name=“org.apache.hadoop.hdfs.util.StripedBlockUtil$ChunkByteArray”/>
</Or>
<Bug pattern="EI_EXPOSE_REP,EI_EXPOSE_REP2" />
</Match>
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8b733931/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java
index ed8c41d..836868b 100755
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java
@@ -424,7 +424,7 @@ public class DFSOutputStream extends FSOutputSummer
currentPacket = null;
}
- void enqueueCurrentPacketFull() throws IOException {
+ synchronized void enqueueCurrentPacketFull() throws IOException {
LOG.debug("enqueue full {}, src={}, bytesCurBlock={}, blockSize={},"
+ " appendChunk={}, {}", currentPacket, src, getStreamer()
.getBytesCurBlock(), blockSize, getStreamer().getAppendChunk(),
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8b733931/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedOutputStream.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedOutputStream.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedOutputStream.java
index a8acf25..884fa42 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedOutputStream.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedOutputStream.java
@@ -531,7 +531,7 @@ public class DFSStripedOutputStream extends DFSOutputStream {
}
@Override
- void enqueueCurrentPacketFull() throws IOException {
+ synchronized void enqueueCurrentPacketFull() throws IOException {
LOG.debug("enqueue full {}, src={}, bytesCurBlock={}, blockSize={},"
+ " appendChunk={}, {}", currentPacket, src, getStreamer()
.getBytesCurBlock(), blockSize, getStreamer().getAppendChunk(),
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8b733931/hadoop-hdfs-project/hadoop-hdfs/CHANGES-HDFS-EC-7285.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES-HDFS-EC-7285.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES-HDFS-EC-7285.txt
deleted file mode 100755
index 9949112..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES-HDFS-EC-7285.txt
+++ /dev/null
@@ -1,460 +0,0 @@
- BREAKDOWN OF HDFS-7285 SUBTASKS AND RELATED JIRAS
-
- HDFS-7347. Configurable erasure coding policy for individual files and
- directories ( Zhe Zhang via vinayakumarb )
-
- HDFS-7339. Representing striped block groups in NameNode with hierarchical
- naming protocol ( Zhe Zhang )
-
- HDFS-7652. Process block reports for erasure coded blocks (Zhe Zhang)
-
- HDFS-7716. Erasure Coding: extend BlockInfo to handle EC info (Jing Zhao)
-
- HDFS-7749. Erasure Coding: Add striped block support in INodeFile (Jing Zhao)
-
- HDFS-7837. Erasure Coding: allocate and persist striped blocks in NameNode
- (Jing Zhao via Zhe Zhang)
-
- HDFS-7872. Erasure Coding: INodeFile.dumpTreeRecursively() supports to print
- striped blocks (Takuya Fukudome via jing9)
-
- HDFS-7853. Erasure coding: extend LocatedBlocks to support reading from
- striped files (Jing Zhao)
-
- HDFS-7826. Erasure Coding: Update INodeFile quota computation for striped
- blocks ( Kai Sasaki via jing9 )
-
- HDFS-7912. Erasure Coding: track BlockInfo instead of Block in
- UnderReplicatedBlocks and PendingReplicationBlocks (Jing Zhao)
-
- HDFS-7369. Erasure coding: distribute recovery work for striped blocks to
- DataNode (Zhe Zhang)
-
- HDFS-7864. Erasure Coding: Update safemode calculation for striped blocks
- (GAO Rui via jing9)
-
- HDFS-7827. Erasure Coding: support striped blocks in non-protobuf fsimage
- ( Hui Zheng via jing9 )
-
- HDFS-7616. Add a test for BlockGroup support in FSImage.
- (Takuya Fukudome via szetszwo)
-
- HDFS-7907. Erasure Coding: track invalid, corrupt, and under-recovery striped
- blocks in NameNode (Jing Zhao)
-
- HDFS-8005. Erasure Coding: simplify striped block recovery work computation
- and add tests (Jing Zhao)
-
- HDFS-7617. Add unit tests for editlog transactions for EC
- (Hui Zheng via Zhe Zhang)
-
- HDFS-7839. Erasure coding: implement facilities in NameNode to create and
- manage EC zones (Zhe Zhang)
-
- HDFS-7969. Erasure coding: NameNode support for lease recovery of striped
- block groups. (Zhe Zhang)
-
- HDFS-7782. Erasure coding: pread from files in striped layout.
- (Zhe Zhang and Jing Zhao via Zhe Zhang)
-
- HDFS-8023. Erasure Coding: retrieve eraure coding schema for a file from
- NameNode (vinayakumarb)
-
- HDFS-8074. Define a system-wide default EC schema. (Kai Zheng)
-
- HDFS-8077. Erasure coding: fix bugs in EC zone and symlinks.
- (Jing Zhao and Zhe Zhang via Jing Zhao)
-
- HDFS-8104. Make hard-coded values consistent with the system default schema first before remove them. (Kai Zheng)
-
- HDFS-7889. Subclass DFSOutputStream to support writing striping layout files. (Li Bo via Kai Zheng)
-
- HDFS-8090. Erasure Coding: Add RPC to client-namenode to list all
- ECSchemas loaded in Namenode. (vinayakumarb)
-
- HDFS-8122. Erasure Coding: Support specifying ECSchema during creation of ECZone.
- (Vinayakumar B via Zhe Zhang)
-
- HDFS-8114. Erasure coding: Add auditlog FSNamesystem#createErasureCodingZone if this
- operation fails. (Rakesh R via Zhe Zhang)
-
- HDFS-8123. Erasure Coding: Better to move EC related proto messages to a
- separate erasurecoding proto file (Rakesh R via vinayakumarb)
-
- HDFS-7349. Support DFS command for the EC encoding (vinayakumarb)
-
- HDFS-8120. Erasure coding: created util class to analyze striped block groups.
- (Contributed by Zhe Zhang and Li Bo via Jing Zhao)
-
- HDFS-7994. Detect if resevered EC Block ID is already used during namenode
- startup. (Hui Zheng via szetszwo)
-
- HDFS-8167. BlockManager.addBlockCollectionWithCheck should check if the block is a striped block. (Hui Zheng via zhz).
-
- HDFS-8166. DFSStripedOutputStream should not create empty blocks. (Jing Zhao)
-
- HDFS-7937. Erasure Coding: INodeFile quota computation unit tests.
- (Kai Sasaki via Jing Zhao)
-
- HDFS-8145. Fix the editlog corruption exposed by failed TestAddStripedBlocks.
- (Jing Zhao)
-
- HDFS-8146. Protobuf changes for BlockECRecoveryCommand and its fields for
- making it ready for transfer to DN (Uma Maheswara Rao G via vinayakumarb)
-
- HDFS-8181. createErasureCodingZone sets retryCache state as false always
- (Uma Maheswara Rao G via vinayakumarb)
-
- HDFS-8190. StripedBlockUtil.getInternalBlockLength may have overflow error.
- (szetszwo)
-
- HDFS-8216. TestDFSStripedOutputStream should use BlockReaderTestUtil to
- create BlockReader. (szetszwo via Zhe Zhang)
-
- HDFS-8212. DistributedFileSystem.createErasureCodingZone should pass schema
- in FileSystemLinkResolver. (szetszwo via Zhe Zhang)
-
- HDFS-8024. Erasure Coding: ECworker frame, basics, bootstraping and configuration.
- (umamahesh)
-
- HDFS-8156. Add/implement necessary APIs even we just have the system default
- schema. (Kai Zheng via Zhe Zhang)
-
- HDFS-8136. Client gets and uses EC schema when reads and writes a stripping
- file. (Kai Sasaki via Kai Zheng)
-
- HDFS-8233. Fix DFSStripedOutputStream#getCurrentBlockGroupBytes when the last
- stripe is at the block group boundary. (jing9)
-
- HDFS-8223. Should calculate checksum for parity blocks in DFSStripedOutputStream.
- (Yi Liu via jing9)
-
- HDFS-8228. Erasure Coding: SequentialBlockGroupIdGenerator#nextValue may cause
- block id conflicts (Jing Zhao via Zhe Zhang)
-
- HDFS-8033. Erasure coding: stateful (non-positional) read from files in
- striped layout (Zhe Zhang)
-
- HDFS-8230. Erasure Coding: Ignore DatanodeProtocol#DNA_ERASURE_CODING_RECOVERY
- commands from standbynode if any (vinayakumarb)
-
- HDFS-8189. ClientProtocol#createErasureCodingZone API was wrongly annotated
- as Idempotent (vinayakumarb)
-
- HDFS-8235. Erasure Coding: Create DFSStripedInputStream in DFSClient#open.
- (Kai Sasaki via jing9)
-
- HDFS-8272. Erasure Coding: simplify the retry logic in DFSStripedInputStream
- (stateful read). (Jing Zhao via Zhe Zhang)
-
- HDFS-8282. Erasure coding: move striped reading logic to StripedBlockUtil.
- (Zhe Zhang)
-
- HDFS-8183. Erasure Coding: Improve DFSStripedOutputStream closing of
- datastreamer threads. (Rakesh R via Zhe Zhang)
-
- HDFS-8308. Erasure Coding: NameNode may get blocked in waitForLoadingFSImage()
- when loading editlog. (jing9)
-
- HDFS-7949. WebImageViewer need support file size calculation with striped
- blocks. (Rakesh R via Zhe Zhang)
-
- HDFS-8316. Erasure coding: refactor EC constants to be consistent with HDFS-8249.
- (Zhe Zhang via jing9)
-
- HDFS-8281. Erasure Coding: implement parallel stateful reading for striped layout.
- (jing9)
-
- HDFS-8137. Send the EC schema to DataNode via EC encoding/recovering command(umamahesh)
-
- HDFS-8242. Erasure Coding: XML based end-to-end test for ECCli commands
- (Rakesh R via vinayakumarb)
-
- HDFS-8324. Add trace info to DFSClient#getErasureCodingZoneInfo(..) (vinayakumarb via
- umamahesh)
-
- HDFS-7672. Handle write failure for stripping blocks and refactor the
- existing code in DFSStripedOutputStream and StripedDataStreamer. (szetszwo)
-
- HDFS-7348. Erasure Coding: DataNode reconstruct striped blocks.
- (Yi Liu via Zhe Zhang)
-
- HADOOP-11921. Enhance tests for erasure coders. (Kai Zheng)
-
- HDFS-8334. Erasure coding: rename DFSStripedInputStream related test
- classes. (Zhe Zhang)
-
- HDFS-8129. Erasure Coding: Maintain consistent naming for Erasure Coding related classes - EC/ErasureCoding
- (umamahesh)
-
- HDFS-8203. Erasure Coding: Seek and other Ops in DFSStripedInputStream.
- (Yi Liu via jing9)
-
- HDFS-8289. Erasure Coding: add ECSchema to HdfsFileStatus. (Yong Zhang via
- jing9)
-
- HDFS-8355. Erasure Coding: Refactor BlockInfo and BlockInfoUnderConstruction.
- (Tsz Wo Nicholas Sze via jing9)
-
- HDFS-7678. Erasure coding: DFSInputStream with decode functionality (pread).
- (Zhe Zhang)
-
- HDFS-8372. Erasure coding: compute storage type quotas for striped files,
- to be consistent with HDFS-8327. (Zhe Zhang via jing9)
-
- HDFS-8368. Erasure Coding: DFS opening a non-existent file need to be
- handled properly (Rakesh R via zhz)
-
- HDFS-8363. Erasure Coding: DFSStripedInputStream#seekToNewSource. (yliu)
-
- HDFS-8195. Erasure coding: Fix file quota change when we complete/commit
- the striped blocks. (Takuya Fukudome via zhz)
-
- HDFS-8364. Erasure coding: fix some minor bugs in EC CLI
- (Walter Su via vinayakumarb)
-
- HDFS-8391. NN should consider current EC tasks handling count from DN while
- assigning new tasks. (umamahesh)
-
- HDFS-8367. BlockInfoStriped uses EC schema. (Kai Sasaki via Kai Zheng)
-
- HDFS-8352. Erasure Coding: test webhdfs read write stripe file. (waltersu4549)
-
- HDFS-8417. Erasure Coding: Pread failed to read data starting from not-first stripe.
- (Walter Su via jing9)
-
- HDFS-8418. Fix the isNeededReplication calculation for Striped block in NN.
- (Yi Liu via jing9)
-
- HDFS-8320. Erasure coding: consolidate striping-related terminologies. (zhz)
-
- HDFS-8366. Erasure Coding: Make the timeout parameter of polling blocking queue
- configurable in DFSStripedOutputStream. (Li Bo)
-
- HDFS-8378. Erasure Coding: Few improvements for the erasure coding worker.
- (Rakesh R via waltersu4549)
-
- HDFS-8375. Add cellSize as an XAttr to ECZone. ( Vinayakumar B via zhz).
-
- HDFS-8428. Erasure Coding: Fix the NullPointerException when deleting file.
- (Yi Liu via zhz).
-
- HDFS-8323. Bump GenerationStamp for write faliure in DFSStripedOutputStream.
- (Tsz Wo Nicholas Sze via jing9)
-
- HDFS-8427. Remove dataBlockNum and parityBlockNum from BlockInfoStriped.
- (Kai Sasaki via jing9)
-
- HDFS-8186. Erasure coding: Make block placement policy for EC file configurable.
- (Walter Su via zhz)
-
- HDFS-8294. Erasure Coding: Fix Findbug warnings present in erasure coding.
- (Rakesh R via zhz)
-
- HDFS-8441. Erasure Coding: make condition check earlier for setReplication.
- (waltersu4549)
-
- HDFS-7768. Change fsck to support EC files. (Takanobu Asanuma via szetszwo)
-
- HDFS-8382. Remove chunkSize and initialize from erasure coder. (Kai Zheng)
-
- HDFS-8408. Revisit and refactor ErasureCodingInfo (vinayakumarb)
-
- HDFS-8479. Erasure coding: fix striping related logic in FSDirWriteFileOp to
- sync with HDFS-8421. (Zhe Zhang via jing9)
-
- HDFS-8481. Erasure coding: remove workarounds in client side stripped blocks
- recovering. (zhz)
-
- HDFS-8336. Expose some administrative erasure coding operations to HdfsAdmin
- (Uma Maheswara Rao G via vinayakumarb)
-
- HDFS-8444. Erasure Coding: fix cannot rename a zone dir
- (Walter Su via vinayakumarb)
-
- HDFS-8517. Fix a decoding issue in stripped block recovering in client side.
- (Kai Zheng via jing9)
-
- HDFS-8453. Erasure coding: properly handle start offset for internal blocks
- in a block group. (Zhe Zhang via jing9)
-
- HDFS-7621. Erasure Coding: update the Balancer/Mover data migration logic.
- (Walter Su via zhz)
-
- HDFS-8328. Follow-on to update decode for DataNode striped blocks
- reconstruction. (yliu)
-
- HDFS-8319. Erasure Coding: support decoding for stateful read.
- (Jing Zhao via zhz)
-
- HDFS-8460. Erasure Coding: stateful read result doesn't match data
- occasionally because of flawed test. (Walter Su via zhz)
-
- HDFS-8556. Erasure Coding: Fix usage of 'createZone' (vinayakumarb)
-
- HDFS-8571. Fix TestErasureCodingCli test (Vinayakumar B via waltersu4549)
-
- HDFS-8450. Erasure Coding: Consolidate erasure coding zone related
- implementation into a single class (Rakesh R via vinayakumarb)
-
- HDFS-8585. Erasure Coding: Remove dataBlockNum and parityBlockNum from
- StripedBlockProto. (Yi Liu via jing9)
-
- HDFS-8559. Erasure Coding: fix non-protobuf fsimage for striped blocks.
- (Jing Zhao via yliu)
-
- HDFS-8580. Erasure coding: Persist cellSize in BlockInfoStriped and
- StripedBlocksFeature. (Walter Su via jing9)
-
- HDFS-8466. Refactor BlockInfoContiguous and fix NPE in
- TestBlockInfo#testCopyConstructor() (vinayakumarb)
-
- HDFS-8254. Avoid assigning a leading streamer in StripedDataStreamer to
- tolerate datanode failure. (Tsz Wo Nicholas Sze via jing9)
-
- HDFS-8543. Erasure Coding: processOverReplicatedBlock() handles striped block.
- (Walter Su via jing9)
-
- HDFS-8602. Erasure Coding: Client can't read(decode) the EC files which have
- corrupt blocks. (jing9 and Kai Sasaki)
-
- HDFS-8567. Erasure Coding: SafeMode handles file smaller than a full stripe.
- (Walter Su via jing9)
-
- HDFS-8253. DFSStripedOutputStream.closeThreads releases cellBuffers
- multiple times. (Kai Sasaki via szetszwo)
-
- HDFS-8468. 2 RPC calls for every file read in DFSClient#open(..) resulting in
- double Audit log entries (vinayakumarb)
-
- HDFS-8684. Erasure Coding: fix some block number calculation for striped
- block. (yliu)
-
- HDFS-8461. Erasure coding: fix priority level of UnderReplicatedBlocks for
- striped block. (Walter Su via jing9)
-
- HDFS-8719. Erasure Coding: client generates too many small packets when
- writing parity data. (Li Bo via waltersu4549)
-
- HDFS-8563. Erasure Coding: fsck handles file smaller than a full stripe.
- (Walter Su via jing9)
-
- HDFS-8484. Erasure coding: Two contiguous blocks occupy IDs belong to same
- striped group. (Walter Su via jing9)
-
- HDFS-8744. Erasure Coding: the number of chunks in packet is not updated
- when writing parity data. (Li Bo)
-
- HDFS-8669. Erasure Coding: handle missing internal block locations in
- DFSStripedInputStream. (jing9)
-
- HDFS-8702. Erasure coding: update BlockManager.blockHasEnoughRacks(..) logic
- for striped block. (Kai Sasaki via jing9)
-
- HDFS-8734. Erasure Coding: fix one cell need two packets. (Walter Su via
- jing9)
-
- HDFS-8619. Erasure Coding: revisit replica counting for striped blocks.
- (Jing Zhao via yliu)
-
- HDFS-8058. Erasure coding: use BlockInfo[] for both striped and contiguous
- blocks in INodeFile. (Zhe Zhang and Yi Liu via zhz)
-
- HDFS-8787. Erasure coding: rename BlockInfoContiguousUC and BlockInfoStripedUC
- to be consistent with trunk. (zhz)
-
- HDFS-8433. Erasure coding: set blockToken in LocatedStripedBlock.(waltersu4549)
-
- HDFS-8760. Erasure Coding: reuse BlockReader when reading the same block in pread.
- (jing9)
-
- HDFS-8781. Erasure Coding: Correctly handle BlockManager#InvalidateBlocks for
- striped block. (Yi Liu via jing9)
-
- HDFS-8813. Erasure Coding: Client no need to decode missing parity blocks.
- (Walter Su via jing9)
-
- HDFS-8798. Erasure Coding: fix DFSStripedInputStream/DFSStripedOutputStream
- re-fetch token when expired. (Walter Su via jing9)
-
- HDFS-8769. Erasure coding: unit test for SequentialBlockGroupIdGenerator.
- (Rakesh R via waltersu4549)
-
- HDFS-8202. Improve end to end stirpping file test to add erasure recovering
- test. (Xinwei Qin via zhz)
-
- HDFS-8804. Erasure Coding: use DirectBufferPool in DFSStripedInputStream for
- buffer allocation. (jing9)
-
- HDFS-8399. Erasure Coding: unit test the behaviour of BlockManager recovery
- work for the deleted blocks. (Rakesh R via zhz)
-
- HDFS-8857. Erasure Coding: Fix ArrayIndexOutOfBoundsException in
- TestWriteStripedFileWithFailure. (Li Bo)
-
- HDFS-8827. Erasure Coding: Fix NPE when NameNode processes over-replicated
- striped blocks. (Walter Su and Takuya Fukudome via jing9)
-
- HDFS-8854. Erasure coding: add ECPolicy to replace schema+cellSize in
- hadoop-hdfs. (Walter Su via zhz)
-
- HDFS-8220. Erasure Coding: StripedDataStreamer fails to handle the
- blocklocations which doesn't satisfy BlockGroupSize. (Rakesh R via zhz)
-
- HDFS-8838. Erasure Coding: Tolerate datanode failures in DFSStripedOutputStream
- when the data length is small. (szetszwo via waltersu4549)
-
- HDFS-8909. Erasure coding: update BlockInfoContiguousUC and BlockInfoStripedUC
- to use BlockUnderConstructionFeature. (Jing Zhao via waltersu4549)
-
- HDFS-8937. Erasure coding: do not throw exception when setting replication on
- EC file. (Gao Rui via jing9)
-
- HDFS-8978. Erasure coding: fix 2 failed tests of DFSStripedOutputStream.
- (Walter Su via jing9)
-
- HDFS-8833. Erasure coding: store EC schema and cell size in INodeFile and
- eliminate notion of EC zones. (zhz)
-
- HDFS-8853. Erasure Coding: Provide ECSchema validation when setting EC
- policy. (andreina via zhz)
-
- HDFS-8975. Erasure coding : Fix random failure in TestSafeModeWithStripedFile
- (J.Andreina via vinayakumarb)
-
- HDFS-7351. Document the HDFS Erasure Coding feature.
- (umamahesh and Zhe Zhang via wang)
-
- HDFS-8899. Erasure Coding: use threadpool for EC recovery tasks on DataNode.
- (Rakesh R via zhz)
-
- HDFS-9088. Cleanup erasure coding documentation. (wang via zhz)
-
- HDFS-9097. Erasure coding: update EC command "-s" flag to "-p" when
- specifying policy. (zhz)
-
- HDFS-9086. Rename dfs.datanode.stripedread.threshold.millis to
- dfs.datanode.stripedread.timeout.millis. (wang via zhz)
-
- HDFS-8550. Erasure Coding: Fix FindBugs Multithreaded correctness Warning.
- (Rakesh R via zhz)
-
- HDFS-9113. ErasureCodingWorker#processErasureCodingTasks should not fail to process
- remaining tasks due to one invalid ECTask (umamahesh)
-
- HDFS-9091. Erasure Coding: Provide DistributedFilesystem API to
- getAllErasureCodingPolicies. (Rakesh R via zhz)
-
- HDFS-8920. Erasure Coding: when recovering lost blocks, logs can be too
- verbose and hurt performance. (Rui Li via Kai Zheng)
-
- HDFS-8882. Erasure Coding: Use datablocks, parityblocks and cell size from
- ErasureCodingPolicy (Vinayakumar B via zhz)
-
- HDFS-9040. Erasure coding: coordinate data streamers in
- DFSStripedOutputStream. (jing9 and Walter Su)
-
- HDFS-9185. Fix null tracer in ErasureCodingWorker. (Rakesh R via jing9)
-
- HDFS-9180. Update excluded DataNodes in DFSStripedOutputStream based on failures
- in data streamers. (jing9)
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8b733931/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index bbf3177..dcd4252 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -170,6 +170,9 @@ Trunk (Unreleased)
HDFS-5033. Bad error message for fs -put/copyFromLocal if user
doesn't have permissions to read the source (Darrell Taylor via aw)
+ HDFS-9182. Cleanup the findbugs and other issues after HDFS EC merged to trunk.
+ (umamahesh)
+
OPTIMIZATIONS
BUG FIXES
@@ -350,6 +353,467 @@ Trunk (Unreleased)
HDFS-8800. hdfs --daemon stop namenode corrupts logs (John Smith via aw)
+ BREAKDOWN OF HDFS-7285 SUBTASKS AND RELATED JIRAS
+
+ HDFS-7347. Configurable erasure coding policy for individual files and
+ directories ( Zhe Zhang via vinayakumarb )
+
+ HDFS-7339. Representing striped block groups in NameNode with hierarchical
+ naming protocol ( Zhe Zhang )
+
+ HDFS-7652. Process block reports for erasure coded blocks (Zhe Zhang)
+
+ HDFS-7716. Erasure Coding: extend BlockInfo to handle EC info (Jing Zhao)
+
+ HDFS-7749. Erasure Coding: Add striped block support in INodeFile (Jing Zhao)
+
+ HDFS-7837. Erasure Coding: allocate and persist striped blocks in NameNode
+ (Jing Zhao via Zhe Zhang)
+
+ HDFS-7872. Erasure Coding: INodeFile.dumpTreeRecursively() supports to print
+ striped blocks (Takuya Fukudome via jing9)
+
+ HDFS-7853. Erasure coding: extend LocatedBlocks to support reading from
+ striped files (Jing Zhao)
+
+ HDFS-7826. Erasure Coding: Update INodeFile quota computation for striped
+ blocks ( Kai Sasaki via jing9 )
+
+ HDFS-7912. Erasure Coding: track BlockInfo instead of Block in
+ UnderReplicatedBlocks and PendingReplicationBlocks (Jing Zhao)
+
+ HDFS-7369. Erasure coding: distribute recovery work for striped blocks to
+ DataNode (Zhe Zhang)
+
+ HDFS-7864. Erasure Coding: Update safemode calculation for striped blocks
+ (GAO Rui via jing9)
+
+ HDFS-7827. Erasure Coding: support striped blocks in non-protobuf fsimage
+ ( Hui Zheng via jing9 )
+
+ HDFS-7616. Add a test for BlockGroup support in FSImage.
+ (Takuya Fukudome via szetszwo)
+
+ HDFS-7907. Erasure Coding: track invalid, corrupt, and under-recovery striped
+ blocks in NameNode (Jing Zhao)
+
+ HDFS-8005. Erasure Coding: simplify striped block recovery work computation
+ and add tests (Jing Zhao)
+
+ HDFS-7617. Add unit tests for editlog transactions for EC
+ (Hui Zheng via Zhe Zhang)
+
+ HDFS-7839. Erasure coding: implement facilities in NameNode to create and
+ manage EC zones (Zhe Zhang)
+
+ HDFS-7969. Erasure coding: NameNode support for lease recovery of striped
+ block groups. (Zhe Zhang)
+
+ HDFS-7782. Erasure coding: pread from files in striped layout.
+ (Zhe Zhang and Jing Zhao via Zhe Zhang)
+
+ HDFS-8023. Erasure Coding: retrieve eraure coding schema for a file from
+ NameNode (vinayakumarb)
+
+ HDFS-8074. Define a system-wide default EC schema. (Kai Zheng)
+
+ HDFS-8077. Erasure coding: fix bugs in EC zone and symlinks.
+ (Jing Zhao and Zhe Zhang via Jing Zhao)
+
+ HDFS-8104. Make hard-coded values consistent with the system default schema first before remove them. (Kai Zheng)
+
+ HDFS-7889. Subclass DFSOutputStream to support writing striping layout files. (Li Bo via Kai Zheng)
+
+ HDFS-8090. Erasure Coding: Add RPC to client-namenode to list all
+ ECSchemas loaded in Namenode. (vinayakumarb)
+
+ HDFS-8122. Erasure Coding: Support specifying ECSchema during creation of ECZone.
+ (Vinayakumar B via Zhe Zhang)
+
+ HDFS-8114. Erasure coding: Add auditlog FSNamesystem#createErasureCodingZone if this
+ operation fails. (Rakesh R via Zhe Zhang)
+
+ HDFS-8123. Erasure Coding: Better to move EC related proto messages to a
+ separate erasurecoding proto file (Rakesh R via vinayakumarb)
+
+ HDFS-7349. Support DFS command for the EC encoding (vinayakumarb)
+
+ HDFS-8120. Erasure coding: created util class to analyze striped block groups.
+ (Contributed by Zhe Zhang and Li Bo via Jing Zhao)
+
+ HDFS-7994. Detect if resevered EC Block ID is already used during namenode
+ startup. (Hui Zheng via szetszwo)
+
+ HDFS-8167. BlockManager.addBlockCollectionWithCheck should check if the block is a striped block. (Hui Zheng via zhz).
+
+ HDFS-8166. DFSStripedOutputStream should not create empty blocks. (Jing Zhao)
+
+ HDFS-7937. Erasure Coding: INodeFile quota computation unit tests.
+ (Kai Sasaki via Jing Zhao)
+
+ HDFS-8145. Fix the editlog corruption exposed by failed TestAddStripedBlocks.
+ (Jing Zhao)
+
+ HDFS-8146. Protobuf changes for BlockECRecoveryCommand and its fields for
+ making it ready for transfer to DN (Uma Maheswara Rao G via vinayakumarb)
+
+ HDFS-8181. createErasureCodingZone sets retryCache state as false always
+ (Uma Maheswara Rao G via vinayakumarb)
+
+ HDFS-8190. StripedBlockUtil.getInternalBlockLength may have overflow error.
+ (szetszwo)
+
+ HDFS-8216. TestDFSStripedOutputStream should use BlockReaderTestUtil to
+ create BlockReader. (szetszwo via Zhe Zhang)
+
+ HDFS-8212. DistributedFileSystem.createErasureCodingZone should pass schema
+ in FileSystemLinkResolver. (szetszwo via Zhe Zhang)
+
+ HDFS-8024. Erasure Coding: ECworker frame, basics, bootstraping and configuration.
+ (umamahesh)
+
+ HDFS-8156. Add/implement necessary APIs even we just have the system default
+ schema. (Kai Zheng via Zhe Zhang)
+
+ HDFS-8136. Client gets and uses EC schema when reads and writes a stripping
+ file. (Kai Sasaki via Kai Zheng)
+
+ HDFS-8233. Fix DFSStripedOutputStream#getCurrentBlockGroupBytes when the last
+ stripe is at the block group boundary. (jing9)
+
+ HDFS-8223. Should calculate checksum for parity blocks in DFSStripedOutputStream.
+ (Yi Liu via jing9)
+
+ HDFS-8228. Erasure Coding: SequentialBlockGroupIdGenerator#nextValue may cause
+ block id conflicts (Jing Zhao via Zhe Zhang)
+
+ HDFS-8033. Erasure coding: stateful (non-positional) read from files in
+ striped layout (Zhe Zhang)
+
+ HDFS-8230. Erasure Coding: Ignore DatanodeProtocol#DNA_ERASURE_CODING_RECOVERY
+ commands from standbynode if any (vinayakumarb)
+
+ HDFS-8189. ClientProtocol#createErasureCodingZone API was wrongly annotated
+ as Idempotent (vinayakumarb)
+
+ HDFS-8235. Erasure Coding: Create DFSStripedInputStream in DFSClient#open.
+ (Kai Sasaki via jing9)
+
+ HDFS-8272. Erasure Coding: simplify the retry logic in DFSStripedInputStream
+ (stateful read). (Jing Zhao via Zhe Zhang)
+
+ HDFS-8282. Erasure coding: move striped reading logic to StripedBlockUtil.
+ (Zhe Zhang)
+
+ HDFS-8183. Erasure Coding: Improve DFSStripedOutputStream closing of
+ datastreamer threads. (Rakesh R via Zhe Zhang)
+
+ HDFS-8308. Erasure Coding: NameNode may get blocked in waitForLoadingFSImage()
+ when loading editlog. (jing9)
+
+ HDFS-7949. WebImageViewer need support file size calculation with striped
+ blocks. (Rakesh R via Zhe Zhang)
+
+ HDFS-8316. Erasure coding: refactor EC constants to be consistent with HDFS-8249.
+ (Zhe Zhang via jing9)
+
+ HDFS-8281. Erasure Coding: implement parallel stateful reading for striped layout.
+ (jing9)
+
+ HDFS-8137. Send the EC schema to DataNode via EC encoding/recovering command(umamahesh)
+
+ HDFS-8242. Erasure Coding: XML based end-to-end test for ECCli commands
+ (Rakesh R via vinayakumarb)
+
+ HDFS-8324. Add trace info to DFSClient#getErasureCodingZoneInfo(..) (vinayakumarb via
+ umamahesh)
+
+ HDFS-7672. Handle write failure for stripping blocks and refactor the
+ existing code in DFSStripedOutputStream and StripedDataStreamer. (szetszwo)
+
+ HDFS-7348. Erasure Coding: DataNode reconstruct striped blocks.
+ (Yi Liu via Zhe Zhang)
+
+ HDFS-8334. Erasure coding: rename DFSStripedInputStream related test
+ classes. (Zhe Zhang)
+
+ HDFS-8129. Erasure Coding: Maintain consistent naming for Erasure Coding related classes - EC/ErasureCoding
+ (umamahesh)
+
+ HDFS-8203. Erasure Coding: Seek and other Ops in DFSStripedInputStream.
+ (Yi Liu via jing9)
+
+ HDFS-8289. Erasure Coding: add ECSchema to HdfsFileStatus. (Yong Zhang via
+ jing9)
+
+ HDFS-8355. Erasure Coding: Refactor BlockInfo and BlockInfoUnderConstruction.
+ (Tsz Wo Nicholas Sze via jing9)
+
+ HDFS-7678. Erasure coding: DFSInputStream with decode functionality (pread).
+ (Zhe Zhang)
+
+ HDFS-8372. Erasure coding: compute storage type quotas for striped files,
+ to be consistent with HDFS-8327. (Zhe Zhang via jing9)
+
+ HDFS-8368. Erasure Coding: DFS opening a non-existent file need to be
+ handled properly (Rakesh R via zhz)
+
+ HDFS-8363. Erasure Coding: DFSStripedInputStream#seekToNewSource. (yliu)
+
+ HDFS-8195. Erasure coding: Fix file quota change when we complete/commit
+ the striped blocks. (Takuya Fukudome via zhz)
+
+ HDFS-8364. Erasure coding: fix some minor bugs in EC CLI
+ (Walter Su via vinayakumarb)
+
+ HDFS-8391. NN should consider current EC tasks handling count from DN while
+ assigning new tasks. (umamahesh)
+
+ HDFS-8367. BlockInfoStriped uses EC schema. (Kai Sasaki via Kai Zheng)
+
+ HDFS-8352. Erasure Coding: test webhdfs read write stripe file. (waltersu4549)
+
+ HDFS-8417. Erasure Coding: Pread failed to read data starting from not-first stripe.
+ (Walter Su via jing9)
+
+ HDFS-8418. Fix the isNeededReplication calculation for Striped block in NN.
+ (Yi Liu via jing9)
+
+ HDFS-8320. Erasure coding: consolidate striping-related terminologies. (zhz)
+
+ HDFS-8366. Erasure Coding: Make the timeout parameter of polling blocking queue
+ configurable in DFSStripedOutputStream. (Li Bo)
+
+ HDFS-8378. Erasure Coding: Few improvements for the erasure coding worker.
+ (Rakesh R via waltersu4549)
+
+ HDFS-8375. Add cellSize as an XAttr to ECZone. ( Vinayakumar B via zhz).
+
+ HDFS-8428. Erasure Coding: Fix the NullPointerException when deleting file.
+ (Yi Liu via zhz).
+
+ HDFS-8323. Bump GenerationStamp for write faliure in DFSStripedOutputStream.
+ (Tsz Wo Nicholas Sze via jing9)
+
+ HDFS-8427. Remove dataBlockNum and parityBlockNum from BlockInfoStriped.
+ (Kai Sasaki via jing9)
+
+ HDFS-8186. Erasure coding: Make block placement policy for EC file configurable.
+ (Walter Su via zhz)
+
+ HDFS-8294. Erasure Coding: Fix Findbug warnings present in erasure coding.
+ (Rakesh R via zhz)
+
+ HDFS-8441. Erasure Coding: make condition check earlier for setReplication.
+ (waltersu4549)
+
+ HDFS-7768. Change fsck to support EC files. (Takanobu Asanuma via szetszwo)
+
+ HDFS-8382. Remove chunkSize and initialize from erasure coder. (Kai Zheng)
+
+ HDFS-8408. Revisit and refactor ErasureCodingInfo (vinayakumarb)
+
+ HDFS-8479. Erasure coding: fix striping related logic in FSDirWriteFileOp to
+ sync with HDFS-8421. (Zhe Zhang via jing9)
+
+ HDFS-8481. Erasure coding: remove workarounds in client side stripped blocks
+ recovering. (zhz)
+
+ HDFS-8336. Expose some administrative erasure coding operations to HdfsAdmin
+ (Uma Maheswara Rao G via vinayakumarb)
+
+ HDFS-8444. Erasure Coding: fix cannot rename a zone dir
+ (Walter Su via vinayakumarb)
+
+ HDFS-8517. Fix a decoding issue in stripped block recovering in client side.
+ (Kai Zheng via jing9)
+
+ HDFS-8453. Erasure coding: properly handle start offset for internal blocks
+ in a block group. (Zhe Zhang via jing9)
+
+ HDFS-7621. Erasure Coding: update the Balancer/Mover data migration logic.
+ (Walter Su via zhz)
+
+ HDFS-8328. Follow-on to update decode for DataNode striped blocks
+ reconstruction. (yliu)
+
+ HDFS-8319. Erasure Coding: support decoding for stateful read.
+ (Jing Zhao via zhz)
+
+ HDFS-8460. Erasure Coding: stateful read result doesn't match data
+ occasionally because of flawed test. (Walter Su via zhz)
+
+ HDFS-8556. Erasure Coding: Fix usage of 'createZone' (vinayakumarb)
+
+ HDFS-8571. Fix TestErasureCodingCli test (Vinayakumar B via waltersu4549)
+
+ HDFS-8450. Erasure Coding: Consolidate erasure coding zone related
+ implementation into a single class (Rakesh R via vinayakumarb)
+
+ HDFS-8585. Erasure Coding: Remove dataBlockNum and parityBlockNum from
+ StripedBlockProto. (Yi Liu via jing9)
+
+ HDFS-8559. Erasure Coding: fix non-protobuf fsimage for striped blocks.
+ (Jing Zhao via yliu)
+
+ HDFS-8580. Erasure coding: Persist cellSize in BlockInfoStriped and
+ StripedBlocksFeature. (Walter Su via jing9)
+
+ HDFS-8466. Refactor BlockInfoContiguous and fix NPE in
+ TestBlockInfo#testCopyConstructor() (vinayakumarb)
+
+ HDFS-8254. Avoid assigning a leading streamer in StripedDataStreamer to
+ tolerate datanode failure. (Tsz Wo Nicholas Sze via jing9)
+
+ HDFS-8543. Erasure Coding: processOverReplicatedBlock() handles striped block.
+ (Walter Su via jing9)
+
+ HDFS-8602. Erasure Coding: Client can't read(decode) the EC files which have
+ corrupt blocks. (jing9 and Kai Sasaki)
+
+ HDFS-8567. Erasure Coding: SafeMode handles file smaller than a full stripe.
+ (Walter Su via jing9)
+
+ HDFS-8253. DFSStripedOutputStream.closeThreads releases cellBuffers
+ multiple times. (Kai Sasaki via szetszwo)
+
+ HDFS-8468. 2 RPC calls for every file read in DFSClient#open(..) resulting in
+ double Audit log entries (vinayakumarb)
+
+ HDFS-8684. Erasure Coding: fix some block number calculation for striped
+ block. (yliu)
+
+ HDFS-8461. Erasure coding: fix priority level of UnderReplicatedBlocks for
+ striped block. (Walter Su via jing9)
+
+ HDFS-8719. Erasure Coding: client generates too many small packets when
+ writing parity data. (Li Bo via waltersu4549)
+
+ HDFS-8563. Erasure Coding: fsck handles file smaller than a full stripe.
+ (Walter Su via jing9)
+
+ HDFS-8484. Erasure coding: Two contiguous blocks occupy IDs belong to same
+ striped group. (Walter Su via jing9)
+
+ HDFS-8744. Erasure Coding: the number of chunks in packet is not updated
+ when writing parity data. (Li Bo)
+
+ HDFS-8669. Erasure Coding: handle missing internal block locations in
+ DFSStripedInputStream. (jing9)
+
+ HDFS-8702. Erasure coding: update BlockManager.blockHasEnoughRacks(..) logic
+ for striped block. (Kai Sasaki via jing9)
+
+ HDFS-8734. Erasure Coding: fix one cell need two packets. (Walter Su via
+ jing9)
+
+ HDFS-8619. Erasure Coding: revisit replica counting for striped blocks.
+ (Jing Zhao via yliu)
+
+ HDFS-8058. Erasure coding: use BlockInfo[] for both striped and contiguous
+ blocks in INodeFile. (Zhe Zhang and Yi Liu via zhz)
+
+ HDFS-8787. Erasure coding: rename BlockInfoContiguousUC and BlockInfoStripedUC
+ to be consistent with trunk. (zhz)
+
+ HDFS-8433. Erasure coding: set blockToken in LocatedStripedBlock.(waltersu4549)
+
+ HDFS-8760. Erasure Coding: reuse BlockReader when reading the same block in pread.
+ (jing9)
+
+ HDFS-8781. Erasure Coding: Correctly handle BlockManager#InvalidateBlocks for
+ striped block. (Yi Liu via jing9)
+
+ HDFS-8813. Erasure Coding: Client no need to decode missing parity blocks.
+ (Walter Su via jing9)
+
+ HDFS-8798. Erasure Coding: fix DFSStripedInputStream/DFSStripedOutputStream
+ re-fetch token when expired. (Walter Su via jing9)
+
+ HDFS-8769. Erasure coding: unit test for SequentialBlockGroupIdGenerator.
+ (Rakesh R via waltersu4549)
+
+ HDFS-8202. Improve end to end stirpping file test to add erasure recovering
+ test. (Xinwei Qin via zhz)
+
+ HDFS-8804. Erasure Coding: use DirectBufferPool in DFSStripedInputStream for
+ buffer allocation. (jing9)
+
+ HDFS-8399. Erasure Coding: unit test the behaviour of BlockManager recovery
+ work for the deleted blocks. (Rakesh R via zhz)
+
+ HDFS-8857. Erasure Coding: Fix ArrayIndexOutOfBoundsException in
+ TestWriteStripedFileWithFailure. (Li Bo)
+
+ HDFS-8827. Erasure Coding: Fix NPE when NameNode processes over-replicated
+ striped blocks. (Walter Su and Takuya Fukudome via jing9)
+
+ HDFS-8854. Erasure coding: add ECPolicy to replace schema+cellSize in
+ hadoop-hdfs. (Walter Su via zhz)
+
+ HDFS-8220. Erasure Coding: StripedDataStreamer fails to handle the
+ blocklocations which doesn't satisfy BlockGroupSize. (Rakesh R via zhz)
+
+ HDFS-8838. Erasure Coding: Tolerate datanode failures in DFSStripedOutputStream
+ when the data length is small. (szetszwo via waltersu4549)
+
+ HDFS-8909. Erasure coding: update BlockInfoContiguousUC and BlockInfoStripedUC
+ to use BlockUnderConstructionFeature. (Jing Zhao via waltersu4549)
+
+ HDFS-8937. Erasure coding: do not throw exception when setting replication on
+ EC file. (Gao Rui via jing9)
+
+ HDFS-8978. Erasure coding: fix 2 failed tests of DFSStripedOutputStream.
+ (Walter Su via jing9)
+
+ HDFS-8833. Erasure coding: store EC schema and cell size in INodeFile and
+ eliminate notion of EC zones. (zhz)
+
+ HDFS-8853. Erasure Coding: Provide ECSchema validation when setting EC
+ policy. (andreina via zhz)
+
+ HDFS-8975. Erasure coding : Fix random failure in TestSafeModeWithStripedFile
+ (J.Andreina via vinayakumarb)
+
+ HDFS-7351. Document the HDFS Erasure Coding feature.
+ (umamahesh and Zhe Zhang via wang)
+
+ HDFS-8899. Erasure Coding: use threadpool for EC recovery tasks on DataNode.
+ (Rakesh R via zhz)
+
+ HDFS-9088. Cleanup erasure coding documentation. (wang via zhz)
+
+ HDFS-9097. Erasure coding: update EC command "-s" flag to "-p" when
+ specifying policy. (zhz)
+
+ HDFS-9086. Rename dfs.datanode.stripedread.threshold.millis to
+ dfs.datanode.stripedread.timeout.millis. (wang via zhz)
+
+ HDFS-8550. Erasure Coding: Fix FindBugs Multithreaded correctness Warning.
+ (Rakesh R via zhz)
+
+ HDFS-9113. ErasureCodingWorker#processErasureCodingTasks should not fail to process
+ remaining tasks due to one invalid ECTask (umamahesh)
+
+ HDFS-9091. Erasure Coding: Provide DistributedFilesystem API to
+ getAllErasureCodingPolicies. (Rakesh R via zhz)
+
+ HDFS-8920. Erasure Coding: when recovering lost blocks, logs can be too
+ verbose and hurt performance. (Rui Li via Kai Zheng)
+
+ HDFS-8882. Erasure Coding: Use datablocks, parityblocks and cell size from
+ ErasureCodingPolicy (Vinayakumar B via zhz)
+
+ HDFS-9040. Erasure coding: coordinate data streamers in
+ DFSStripedOutputStream. (jing9 and Walter Su)
+
+ HDFS-9185. Fix null tracer in ErasureCodingWorker. (Rakesh R via jing9)
+
+ HDFS-9180. Update excluded DataNodes in DFSStripedOutputStream based on failures
+ in data streamers. (jing9)
+
+ HDFS-8557. Allow to configure RS and XOR raw coders (Kai Zheng)
+
Release 2.8.0 - UNRELEASED
NEW FEATURES
[25/35] hadoop git commit: HDFS-9159. [OIV] : return value of the
command is not correct if invalid value specified in '-p (processor)' option
(Contributed by nijel)
Posted by ji...@apache.org.
HDFS-9159. [OIV] : return value of the command is not correct if invalid value specified in '-p (processor)' option (Contributed by nijel)
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/61b3547c
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/61b3547c
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/61b3547c
Branch: refs/heads/HDFS-8966
Commit: 61b3547c462a4e51d0a31c0a8c8ce210e2d90df8
Parents: 3112f26
Author: Vinayakumar B <vi...@apache.org>
Authored: Wed Oct 7 14:29:34 2015 +0530
Committer: Vinayakumar B <vi...@apache.org>
Committed: Wed Oct 7 14:29:34 2015 +0530
----------------------------------------------------------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +++
.../hdfs/tools/offlineImageViewer/OfflineImageViewerPB.java | 4 ++++
.../tools/offlineImageViewer/TestOfflineImageViewer.java | 9 +++++++++
3 files changed, 16 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/61b3547c/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 7ed40aa..e495497 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1971,6 +1971,9 @@ Release 2.8.0 - UNRELEASED
HDFS-9196. Fix TestWebHdfsContentLength. (Masatake Iwasaki via jing9)
+ HDFS-9159. [OIV] : return value of the command is not correct if invalid
+ value specified in "-p (processor)" option (nijel via vinayakumarb)
+
Release 2.7.2 - UNRELEASED
INCOMPATIBLE CHANGES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/61b3547c/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageViewerPB.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageViewerPB.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageViewerPB.java
index 4169af1..777acdf 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageViewerPB.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageViewerPB.java
@@ -182,6 +182,10 @@ public class OfflineImageViewerPB {
writer.visit(new RandomAccessFile(inputFile, "r"));
}
break;
+ default:
+ System.err.println("Invalid processor specified : " + processor);
+ printUsage();
+ return -1;
}
return 0;
} catch (EOFException e) {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/61b3547c/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/TestOfflineImageViewer.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/TestOfflineImageViewer.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/TestOfflineImageViewer.java
index a8d1d54..e1beca5 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/TestOfflineImageViewer.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/TestOfflineImageViewer.java
@@ -341,6 +341,15 @@ public class TestOfflineImageViewer {
new FileSystemTestHelper().getTestRootDir() + "/delimited.db");
}
+ @Test
+ public void testInvalidProcessorOption() throws Exception {
+ int status =
+ OfflineImageViewerPB.run(new String[] { "-i",
+ originalFsimage.getAbsolutePath(), "-o", "-", "-p", "invalid" });
+ assertTrue("Exit code returned for invalid processor option is incorrect",
+ status != 0);
+ }
+
private void testPBDelimitedWriter(String db)
throws IOException, InterruptedException {
final String DELIMITER = "\t";
[32/35] hadoop git commit: HDFS-8164. cTime is 0 in VERSION file for
newly formatted NameNode. Contributed by Xiao Chen.
Posted by ji...@apache.org.
HDFS-8164. cTime is 0 in VERSION file for newly formatted NameNode. Contributed by Xiao Chen.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/1107bd39
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/1107bd39
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/1107bd39
Branch: refs/heads/HDFS-8966
Commit: 1107bd399c790467b22e55291c2611fd1c16e156
Parents: 35affec
Author: Yongjun Zhang <yz...@cloudera.com>
Authored: Wed Oct 7 23:20:10 2015 -0700
Committer: Yongjun Zhang <yz...@cloudera.com>
Committed: Wed Oct 7 23:20:10 2015 -0700
----------------------------------------------------------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +++
.../hdfs/server/namenode/FSNamesystem.java | 12 +++++++++
.../hadoop/hdfs/server/namenode/NNStorage.java | 2 +-
.../hdfs/server/namenode/TestFSImage.java | 26 +++++++++++++++++++-
4 files changed, 41 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/1107bd39/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index e05a618..1116f80 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1491,6 +1491,9 @@ Release 2.8.0 - UNRELEASED
HDFS-9170. Move libhdfs / fuse-dfs / libwebhdfs to hdfs-client. (wheat9)
+ HDFS-8164. cTime is 0 in VERSION file for newly formatted NameNode.
+ (Xiao Chen via Yongjun Zhang)
+
OPTIMIZATIONS
HDFS-8026. Trace FSOutputSummer#writeChecksumChunks rather than
http://git-wip-us.apache.org/repos/asf/hadoop/blob/1107bd39/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
index a94b61c..a5b6c77 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
@@ -1521,6 +1521,18 @@ public class FSNamesystem implements Namesystem, FSNamesystemMBean,
}
/**
+ * Get the creation time of the file system.
+ * Notice that this time is initialized to NameNode format time, and updated
+ * to upgrade time during upgrades.
+ * @return time in milliseconds.
+ * See {@link org.apache.hadoop.util.Time#now()}.
+ */
+ @VisibleForTesting
+ long getCTime() {
+ return fsImage == null ? 0 : fsImage.getStorage().getCTime();
+ }
+
+ /**
* Version of @see #getNamespaceInfo() that is not protected by a lock.
*/
NamespaceInfo unprotectedGetNamespaceInfo() {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/1107bd39/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NNStorage.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NNStorage.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NNStorage.java
index 14647f0..d872c03 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NNStorage.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NNStorage.java
@@ -573,7 +573,7 @@ public class NNStorage extends Storage implements Closeable,
public static NamespaceInfo newNamespaceInfo()
throws UnknownHostException {
return new NamespaceInfo(newNamespaceID(), newClusterID(),
- newBlockPoolID(), 0L);
+ newBlockPoolID(), Time.now());
}
public void format() throws IOException {
http://git-wip-us.apache.org/repos/asf/hadoop/blob/1107bd39/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java
index e45d08d..0c7398c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java
@@ -62,6 +62,7 @@ import org.apache.hadoop.hdfs.server.namenode.NNStorage.NameNodeDirType;
import org.apache.hadoop.hdfs.util.MD5FileUtils;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.test.PathUtils;
+import org.apache.hadoop.util.Time;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
@@ -368,7 +369,30 @@ public class TestFSImage {
}
}
}
-
+
+ /**
+ * Ensure ctime is set during namenode formatting.
+ */
+ @Test(timeout=60000)
+ public void testCtime() throws Exception {
+ Configuration conf = new Configuration();
+ MiniDFSCluster cluster = null;
+ try {
+ final long pre = Time.now();
+ cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
+ cluster.waitActive();
+ final long post = Time.now();
+ final long ctime = cluster.getNamesystem().getCTime();
+
+ assertTrue(pre <= ctime);
+ assertTrue(ctime <= post);
+ } finally {
+ if (cluster != null) {
+ cluster.shutdown();
+ }
+ }
+ }
+
/**
* In this test case, I have created an image with a file having
* preferredblockSize = 0. We are trying to read this image (since file with
[16/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/thread_local_storage.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/thread_local_storage.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/thread_local_storage.c
new file mode 100644
index 0000000..2f70e2c
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/thread_local_storage.c
@@ -0,0 +1,80 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "os/thread_local_storage.h"
+
+#include <jni.h>
+#include <pthread.h>
+#include <stdio.h>
+
+/** Key that allows us to retrieve thread-local storage */
+static pthread_key_t gTlsKey;
+
+/** nonzero if we succeeded in initializing gTlsKey. Protected by the jvmMutex */
+static int gTlsKeyInitialized = 0;
+
+/**
+ * The function that is called whenever a thread with libhdfs thread local data
+ * is destroyed.
+ *
+ * @param v The thread-local data
+ */
+static void hdfsThreadDestructor(void *v)
+{
+ JavaVM *vm;
+ JNIEnv *env = v;
+ jint ret;
+
+ ret = (*env)->GetJavaVM(env, &vm);
+ if (ret) {
+ fprintf(stderr, "hdfsThreadDestructor: GetJavaVM failed with error %d\n",
+ ret);
+ (*env)->ExceptionDescribe(env);
+ } else {
+ (*vm)->DetachCurrentThread(vm);
+ }
+}
+
+int threadLocalStorageGet(JNIEnv **env)
+{
+ int ret = 0;
+ if (!gTlsKeyInitialized) {
+ ret = pthread_key_create(&gTlsKey, hdfsThreadDestructor);
+ if (ret) {
+ fprintf(stderr,
+ "threadLocalStorageGet: pthread_key_create failed with error %d\n",
+ ret);
+ return ret;
+ }
+ gTlsKeyInitialized = 1;
+ }
+ *env = pthread_getspecific(gTlsKey);
+ return ret;
+}
+
+int threadLocalStorageSet(JNIEnv *env)
+{
+ int ret = pthread_setspecific(gTlsKey, env);
+ if (ret) {
+ fprintf(stderr,
+ "threadLocalStorageSet: pthread_setspecific failed with error %d\n",
+ ret);
+ hdfsThreadDestructor(env);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/thread.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/thread.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/thread.h
new file mode 100644
index 0000000..ae425d3
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/thread.h
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_THREAD_H
+#define LIBHDFS_THREAD_H
+
+/*
+ * Defines abstraction over platform-specific threads.
+ */
+
+#include "platform.h"
+
+/** Pointer to function to run in thread. */
+typedef void (*threadProcedure)(void *);
+
+/** Structure containing a thread's ID, starting address and argument. */
+typedef struct {
+ threadId id;
+ threadProcedure start;
+ void *arg;
+} thread;
+
+/**
+ * Creates and immediately starts a new thread.
+ *
+ * @param t thread to create
+ * @return 0 if successful, non-zero otherwise
+ */
+int threadCreate(thread *t);
+
+/**
+ * Joins to the given thread, blocking if necessary.
+ *
+ * @param t thread to join
+ * @return 0 if successful, non-zero otherwise
+ */
+int threadJoin(const thread *t);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/thread_local_storage.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/thread_local_storage.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/thread_local_storage.h
new file mode 100644
index 0000000..a40d567
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/thread_local_storage.h
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_THREAD_LOCAL_STORAGE_H
+#define LIBHDFS_THREAD_LOCAL_STORAGE_H
+
+/*
+ * Defines abstraction over platform-specific thread-local storage. libhdfs
+ * currently only needs thread-local storage for a single piece of data: the
+ * thread's JNIEnv. For simplicity, this interface is defined in terms of
+ * JNIEnv, not general-purpose thread-local storage of any arbitrary data.
+ */
+
+#include <jni.h>
+
+/*
+ * Most operating systems support the more efficient __thread construct, which
+ * is initialized by the linker. The following macros use this technique on the
+ * operating systems that support it.
+ */
+#ifdef HAVE_BETTER_TLS
+ #define THREAD_LOCAL_STORAGE_GET_QUICK() \
+ static __thread JNIEnv *quickTlsEnv = NULL; \
+ { \
+ if (quickTlsEnv) { \
+ return quickTlsEnv; \
+ } \
+ }
+
+ #define THREAD_LOCAL_STORAGE_SET_QUICK(env) \
+ { \
+ quickTlsEnv = (env); \
+ }
+#else
+ #define THREAD_LOCAL_STORAGE_GET_QUICK()
+ #define THREAD_LOCAL_STORAGE_SET_QUICK(env)
+#endif
+
+/**
+ * Gets the JNIEnv in thread-local storage for the current thread. If the call
+ * succeeds, and there is a JNIEnv associated with this thread, then returns 0
+ * and populates env. If the call succeeds, but there is no JNIEnv associated
+ * with this thread, then returns 0 and sets JNIEnv to NULL. If the call fails,
+ * then returns non-zero. Only one thread at a time may execute this function.
+ * The caller is responsible for enforcing mutual exclusion.
+ *
+ * @param env JNIEnv out parameter
+ * @return 0 if successful, non-zero otherwise
+ */
+int threadLocalStorageGet(JNIEnv **env);
+
+/**
+ * Sets the JNIEnv in thread-local storage for the current thread.
+ *
+ * @param env JNIEnv to set
+ * @return 0 if successful, non-zero otherwise
+ */
+int threadLocalStorageSet(JNIEnv *env);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/inttypes.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/inttypes.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/inttypes.h
new file mode 100644
index 0000000..a520d15
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/inttypes.h
@@ -0,0 +1,28 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_INTTYPES_H
+#define LIBHDFS_INTTYPES_H
+
+/* On Windows, inttypes.h does not exist, so manually define what we need. */
+
+#define PRId64 "I64d"
+#define PRIu64 "I64u"
+typedef unsigned __int64 uint64_t;
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/mutexes.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/mutexes.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/mutexes.c
new file mode 100644
index 0000000..875f033
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/mutexes.c
@@ -0,0 +1,52 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "os/mutexes.h"
+
+#include <windows.h>
+
+mutex hdfsHashMutex;
+mutex jvmMutex;
+
+/**
+ * Unfortunately, there is no simple static initializer for a critical section.
+ * Instead, the API requires calling InitializeCriticalSection. Since libhdfs
+ * lacks an explicit initialization function, there is no obvious existing place
+ * for the InitializeCriticalSection calls. To work around this, we define an
+ * initialization function and instruct the linker to set a pointer to that
+ * function as a user-defined global initializer. See discussion of CRT
+ * Initialization:
+ * http://msdn.microsoft.com/en-us/library/bb918180.aspx
+ */
+static void __cdecl initializeMutexes(void) {
+ InitializeCriticalSection(&hdfsHashMutex);
+ InitializeCriticalSection(&jvmMutex);
+}
+#pragma section(".CRT$XCU", read)
+__declspec(allocate(".CRT$XCU"))
+const void (__cdecl *pInitialize)(void) = initializeMutexes;
+
+int mutexLock(mutex *m) {
+ EnterCriticalSection(m);
+ return 0;
+}
+
+int mutexUnlock(mutex *m) {
+ LeaveCriticalSection(m);
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/platform.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/platform.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/platform.h
new file mode 100644
index 0000000..9eedfde
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/platform.h
@@ -0,0 +1,86 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_PLATFORM_H
+#define LIBHDFS_PLATFORM_H
+
+#include <stdio.h>
+#include <windows.h>
+#include <winsock.h>
+
+/*
+ * O_ACCMODE defined to match Linux definition.
+ */
+#ifndef O_ACCMODE
+#define O_ACCMODE 0x0003
+#endif
+
+/*
+ * Windows has a different name for its maximum path length constant.
+ */
+#ifndef PATH_MAX
+#define PATH_MAX MAX_PATH
+#endif
+
+/*
+ * Windows does not define EDQUOT and ESTALE in errno.h. The closest equivalents
+ * are these constants from winsock.h.
+ */
+#ifndef EDQUOT
+#define EDQUOT WSAEDQUOT
+#endif
+
+#ifndef ESTALE
+#define ESTALE WSAESTALE
+#endif
+
+/*
+ * gcc-style type-checked format arguments are not supported on Windows, so just
+ * stub this macro.
+ */
+#define TYPE_CHECKED_PRINTF_FORMAT(formatArg, varArgs)
+
+/*
+ * Define macros for various string formatting functions not defined on Windows.
+ * Where possible, we reroute to one of the secure CRT variants. On Windows,
+ * the preprocessor does support variadic macros, even though they weren't
+ * defined until C99.
+ */
+#define snprintf(str, size, format, ...) \
+ _snprintf_s((str), (size), _TRUNCATE, (format), __VA_ARGS__)
+#define strncpy(dest, src, n) \
+ strncpy_s((dest), (n), (src), _TRUNCATE)
+#define strtok_r(str, delim, saveptr) \
+ strtok_s((str), (delim), (saveptr))
+#define vsnprintf(str, size, format, ...) \
+ vsnprintf_s((str), (size), _TRUNCATE, (format), __VA_ARGS__)
+
+/*
+ * Mutex data type defined as Windows CRITICAL_SECTION. A critical section (not
+ * Windows mutex) is used, because libhdfs only needs synchronization of multiple
+ * threads within a single process, not synchronization across process
+ * boundaries.
+ */
+typedef CRITICAL_SECTION mutex;
+
+/*
+ * Thread data type defined as HANDLE to a Windows thread.
+ */
+typedef HANDLE threadId;
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/thread.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/thread.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/thread.c
new file mode 100644
index 0000000..f5cc2a7
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/thread.c
@@ -0,0 +1,66 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "os/thread.h"
+
+#include <stdio.h>
+#include <windows.h>
+
+/**
+ * Defines a helper function that adapts function pointer provided by caller to
+ * the type required by CreateThread.
+ *
+ * @param toRun thread to run
+ * @return DWORD result of running thread (always 0)
+ */
+static DWORD WINAPI runThread(LPVOID toRun) {
+ const thread *t = toRun;
+ t->start(t->arg);
+ return 0;
+}
+
+int threadCreate(thread *t) {
+ DWORD ret = 0;
+ HANDLE h;
+ h = CreateThread(NULL, 0, runThread, t, 0, NULL);
+ if (h) {
+ t->id = h;
+ } else {
+ ret = GetLastError();
+ fprintf(stderr, "threadCreate: CreateThread failed with error %d\n", ret);
+ }
+ return ret;
+}
+
+int threadJoin(const thread *t) {
+ DWORD ret = WaitForSingleObject(t->id, INFINITE);
+ switch (ret) {
+ case WAIT_OBJECT_0:
+ break;
+ case WAIT_FAILED:
+ ret = GetLastError();
+ fprintf(stderr, "threadJoin: WaitForSingleObject failed with error %d\n",
+ ret);
+ break;
+ default:
+ fprintf(stderr, "threadJoin: WaitForSingleObject unexpected error %d\n",
+ ret);
+ break;
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/thread_local_storage.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/thread_local_storage.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/thread_local_storage.c
new file mode 100644
index 0000000..4c415e1
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/thread_local_storage.c
@@ -0,0 +1,172 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "os/thread_local_storage.h"
+
+#include <jni.h>
+#include <stdio.h>
+#include <windows.h>
+
+/** Key that allows us to retrieve thread-local storage */
+static DWORD gTlsIndex = TLS_OUT_OF_INDEXES;
+
+/**
+ * If the current thread has a JNIEnv in thread-local storage, then detaches the
+ * current thread from the JVM.
+ */
+static void detachCurrentThreadFromJvm()
+{
+ JNIEnv *env = NULL;
+ JavaVM *vm;
+ jint ret;
+ if (threadLocalStorageGet(&env) || !env) {
+ return;
+ }
+ ret = (*env)->GetJavaVM(env, &vm);
+ if (ret) {
+ fprintf(stderr,
+ "detachCurrentThreadFromJvm: GetJavaVM failed with error %d\n",
+ ret);
+ (*env)->ExceptionDescribe(env);
+ } else {
+ (*vm)->DetachCurrentThread(vm);
+ }
+}
+
+/**
+ * Unlike pthreads, the Windows API does not seem to provide a convenient way to
+ * hook a callback onto thread shutdown. However, the Windows portable
+ * executable format does define a concept of thread-local storage callbacks.
+ * Here, we define a function and instruct the linker to set a pointer to that
+ * function in the segment for thread-local storage callbacks. See page 85 of
+ * Microsoft Portable Executable and Common Object File Format Specification:
+ * http://msdn.microsoft.com/en-us/gg463119.aspx
+ * This technique only works for implicit linking (OS loads DLL on demand), not
+ * for explicit linking (user code calls LoadLibrary directly). This effectively
+ * means that we have a known limitation: libhdfs may not work correctly if a
+ * Windows application attempts to use it via explicit linking.
+ *
+ * @param h module handle
+ * @param reason the reason for calling the callback
+ * @param pv reserved, unused
+ */
+static void NTAPI tlsCallback(PVOID h, DWORD reason, PVOID pv)
+{
+ DWORD tlsIndex;
+ switch (reason) {
+ case DLL_THREAD_DETACH:
+ detachCurrentThreadFromJvm();
+ break;
+ case DLL_PROCESS_DETACH:
+ detachCurrentThreadFromJvm();
+ tlsIndex = gTlsIndex;
+ gTlsIndex = TLS_OUT_OF_INDEXES;
+ if (!TlsFree(tlsIndex)) {
+ fprintf(stderr, "tlsCallback: TlsFree failed with error %d\n",
+ GetLastError());
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+ * A variable named _tls_used contains the TLS directory, which contains a list
+ * of pointers to callback functions. Normally, the linker won't retain this
+ * variable unless the executable has implicit thread-local variables, defined
+ * using the __declspec(thread) extended storage-class modifier. libhdfs
+ * doesn't use __declspec(thread), and we have no guarantee that the executable
+ * linked to libhdfs will use __declspec(thread). By forcing the linker to
+ * reference _tls_used, we guarantee that the binary retains the TLS directory.
+ * See Microsoft Visual Studio 10.0/VC/crt/src/tlssup.c .
+ */
+#ifdef _WIN64
+#pragma comment(linker, "/INCLUDE:_tls_used")
+#else
+#pragma comment(linker, "/INCLUDE:__tls_used")
+#endif
+
+/*
+ * We must retain a pointer to the callback function. Force the linker to keep
+ * this symbol, even though it appears that nothing in our source code uses it.
+ */
+#ifdef _WIN64
+#pragma comment(linker, "/INCLUDE:pTlsCallback")
+#else
+#pragma comment(linker, "/INCLUDE:_pTlsCallback")
+#endif
+
+/*
+ * Define constant pointer to our callback, and tell the linker to pin it into
+ * the TLS directory so that it receives thread callbacks. Use external linkage
+ * to protect against the linker discarding the seemingly unused symbol.
+ */
+#pragma const_seg(".CRT$XLB")
+extern const PIMAGE_TLS_CALLBACK pTlsCallback;
+const PIMAGE_TLS_CALLBACK pTlsCallback = tlsCallback;
+#pragma const_seg()
+
+int threadLocalStorageGet(JNIEnv **env)
+{
+ LPVOID tls;
+ DWORD ret;
+ if (TLS_OUT_OF_INDEXES == gTlsIndex) {
+ gTlsIndex = TlsAlloc();
+ if (TLS_OUT_OF_INDEXES == gTlsIndex) {
+ fprintf(stderr,
+ "threadLocalStorageGet: TlsAlloc failed with error %d\n",
+ TLS_OUT_OF_INDEXES);
+ return TLS_OUT_OF_INDEXES;
+ }
+ }
+ tls = TlsGetValue(gTlsIndex);
+ if (tls) {
+ *env = tls;
+ return 0;
+ } else {
+ ret = GetLastError();
+ if (ERROR_SUCCESS == ret) {
+ /* Thread-local storage contains NULL, because we haven't set it yet. */
+ *env = NULL;
+ return 0;
+ } else {
+ /*
+ * The API call failed. According to documentation, TlsGetValue cannot
+ * fail as long as the index is a valid index from a successful TlsAlloc
+ * call. This error handling is purely defensive.
+ */
+ fprintf(stderr,
+ "threadLocalStorageGet: TlsGetValue failed with error %d\n", ret);
+ return ret;
+ }
+ }
+}
+
+int threadLocalStorageSet(JNIEnv *env)
+{
+ DWORD ret = 0;
+ if (!TlsSetValue(gTlsIndex, (LPVOID)env)) {
+ ret = GetLastError();
+ fprintf(stderr,
+ "threadLocalStorageSet: TlsSetValue failed with error %d\n",
+ ret);
+ detachCurrentThreadFromJvm(env);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/unistd.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/unistd.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/unistd.h
new file mode 100644
index 0000000..b82ce48
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/windows/unistd.h
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_UNISTD_H
+#define LIBHDFS_UNISTD_H
+
+/* On Windows, unistd.h does not exist, so manually define what we need. */
+
+#include <process.h> /* Declares getpid(). */
+#include <windows.h>
+
+/* Re-route sleep to Sleep, converting units from seconds to milliseconds. */
+#define sleep(seconds) Sleep((seconds) * 1000)
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_htable.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_htable.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_htable.c
new file mode 100644
index 0000000..0c3861b
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_htable.c
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "common/htable.h"
+#include "expect.h"
+#include "hdfs_test.h"
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+// Disable type cast and loss of precision warnings, because the test
+// manipulates void* values manually on purpose.
+#ifdef WIN32
+#pragma warning(disable: 4244 4306)
+#endif
+
+static uint32_t simple_hash(const void *key, uint32_t size)
+{
+ uintptr_t k = (uintptr_t)key;
+ return ((13 + k) * 6367) % size;
+}
+
+static int simple_compare(const void *a, const void *b)
+{
+ return a == b;
+}
+
+static void expect_102(void *f, void *k, void *v)
+{
+ int *found_102 = f;
+ uintptr_t key = (uintptr_t)k;
+ uintptr_t val = (uintptr_t)v;
+
+ if ((key == 2) && (val == 102)) {
+ *found_102 = 1;
+ } else {
+ abort();
+ }
+}
+
+static void *htable_pop_val(struct htable *ht, void *key)
+{
+ void *old_key, *old_val;
+
+ htable_pop(ht, key, &old_key, &old_val);
+ return old_val;
+}
+
+int main(void)
+{
+ struct htable *ht;
+ int found_102 = 0;
+
+ ht = htable_alloc(4, simple_hash, simple_compare);
+ EXPECT_INT_EQ(0, htable_used(ht));
+ EXPECT_INT_EQ(4, htable_capacity(ht));
+ EXPECT_NULL(htable_get(ht, (void*)123));
+ EXPECT_NULL(htable_pop_val(ht, (void*)123));
+ EXPECT_ZERO(htable_put(ht, (void*)123, (void*)456));
+ EXPECT_INT_EQ(456, (uintptr_t)htable_get(ht, (void*)123));
+ EXPECT_INT_EQ(456, (uintptr_t)htable_pop_val(ht, (void*)123));
+ EXPECT_NULL(htable_pop_val(ht, (void*)123));
+
+ // Enlarge the hash table
+ EXPECT_ZERO(htable_put(ht, (void*)1, (void*)101));
+ EXPECT_ZERO(htable_put(ht, (void*)2, (void*)102));
+ EXPECT_ZERO(htable_put(ht, (void*)3, (void*)103));
+ EXPECT_INT_EQ(3, htable_used(ht));
+ EXPECT_INT_EQ(8, htable_capacity(ht));
+ EXPECT_INT_EQ(102, (uintptr_t)htable_get(ht, (void*)2));
+ EXPECT_INT_EQ(101, (uintptr_t)htable_pop_val(ht, (void*)1));
+ EXPECT_INT_EQ(103, (uintptr_t)htable_pop_val(ht, (void*)3));
+ EXPECT_INT_EQ(1, htable_used(ht));
+ htable_visit(ht, expect_102, &found_102);
+ EXPECT_INT_EQ(1, found_102);
+ htable_free(ht);
+
+ fprintf(stderr, "SUCCESS.\n");
+ return EXIT_SUCCESS;
+}
+
+// vim: ts=4:sw=4:tw=79:et
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_ops.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_ops.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_ops.c
new file mode 100644
index 0000000..f564de4
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_ops.c
@@ -0,0 +1,540 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "hdfs.h"
+#include "hdfs_test.h"
+#include "platform.h"
+
+#include <inttypes.h>
+#include <jni.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+void permission_disp(short permissions, char *rtr) {
+ int i;
+ short permissionsId;
+ char* perm;
+ rtr[9] = '\0';
+ for(i=2;i>=0;i--)
+ {
+ permissionsId = permissions >> (i * 3) & (short)7;
+ switch(permissionsId) {
+ case 7:
+ perm = "rwx"; break;
+ case 6:
+ perm = "rw-"; break;
+ case 5:
+ perm = "r-x"; break;
+ case 4:
+ perm = "r--"; break;
+ case 3:
+ perm = "-wx"; break;
+ case 2:
+ perm = "-w-"; break;
+ case 1:
+ perm = "--x"; break;
+ case 0:
+ perm = "---"; break;
+ default:
+ perm = "???";
+ }
+ strncpy(rtr, perm, 3);
+ rtr+=3;
+ }
+}
+
+int main(int argc, char **argv) {
+ const char *writePath = "/tmp/testfile.txt";
+ const char *fileContents = "Hello, World!";
+ const char *readPath = "/tmp/testfile.txt";
+ const char *srcPath = "/tmp/testfile.txt";
+ const char *dstPath = "/tmp/testfile2.txt";
+ const char *slashTmp = "/tmp";
+ const char *newDirectory = "/tmp/newdir";
+ const char *newOwner = "root";
+ const char *tuser = "nobody";
+ const char *appendPath = "/tmp/appends";
+ const char *userPath = "/tmp/usertestfile.txt";
+
+ char buffer[32], buffer2[256], rdbuffer[32];
+ tSize num_written_bytes, num_read_bytes;
+ hdfsFS fs, lfs;
+ hdfsFile writeFile, readFile, localFile, appendFile, userFile;
+ tOffset currentPos, seekPos;
+ int exists, totalResult, result, numEntries, i, j;
+ const char *resp;
+ hdfsFileInfo *fileInfo, *fileList, *finfo;
+ char *buffer3;
+ char permissions[10];
+ char ***hosts;
+ short newPerm = 0666;
+ tTime newMtime, newAtime;
+
+ fs = hdfsConnectNewInstance("default", 0);
+ if(!fs) {
+ fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
+ exit(-1);
+ }
+
+ lfs = hdfsConnectNewInstance(NULL, 0);
+ if(!lfs) {
+ fprintf(stderr, "Oops! Failed to connect to 'local' hdfs!\n");
+ exit(-1);
+ }
+
+ {
+ //Write tests
+
+ writeFile = hdfsOpenFile(fs, writePath, O_WRONLY|O_CREAT, 0, 0, 0);
+ if(!writeFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", writePath);
+ exit(-1);
+ }
+ fprintf(stderr, "Opened %s for writing successfully...\n", writePath);
+ num_written_bytes =
+ hdfsWrite(fs, writeFile, (void*)fileContents,
+ (tSize)(strlen(fileContents)+1));
+ if (num_written_bytes != strlen(fileContents) + 1) {
+ fprintf(stderr, "Failed to write correct number of bytes - expected %d, got %d\n",
+ (int)(strlen(fileContents) + 1), (int)num_written_bytes);
+ exit(-1);
+ }
+ fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
+
+ currentPos = -1;
+ if ((currentPos = hdfsTell(fs, writeFile)) == -1) {
+ fprintf(stderr,
+ "Failed to get current file position correctly! Got %" PRId64 "!\n",
+ currentPos);
+ exit(-1);
+ }
+ fprintf(stderr, "Current position: %" PRId64 "\n", currentPos);
+
+ if (hdfsFlush(fs, writeFile)) {
+ fprintf(stderr, "Failed to 'flush' %s\n", writePath);
+ exit(-1);
+ }
+ fprintf(stderr, "Flushed %s successfully!\n", writePath);
+
+ if (hdfsHFlush(fs, writeFile)) {
+ fprintf(stderr, "Failed to 'hflush' %s\n", writePath);
+ exit(-1);
+ }
+ fprintf(stderr, "HFlushed %s successfully!\n", writePath);
+
+ hdfsCloseFile(fs, writeFile);
+ }
+
+ {
+ //Read tests
+
+ exists = hdfsExists(fs, readPath);
+
+ if (exists) {
+ fprintf(stderr, "Failed to validate existence of %s\n", readPath);
+ exit(-1);
+ }
+
+ readFile = hdfsOpenFile(fs, readPath, O_RDONLY, 0, 0, 0);
+ if (!readFile) {
+ fprintf(stderr, "Failed to open %s for reading!\n", readPath);
+ exit(-1);
+ }
+
+ if (!hdfsFileIsOpenForRead(readFile)) {
+ fprintf(stderr, "hdfsFileIsOpenForRead: we just opened a file "
+ "with O_RDONLY, and it did not show up as 'open for "
+ "read'\n");
+ exit(-1);
+ }
+
+ fprintf(stderr, "hdfsAvailable: %d\n", hdfsAvailable(fs, readFile));
+
+ seekPos = 1;
+ if(hdfsSeek(fs, readFile, seekPos)) {
+ fprintf(stderr, "Failed to seek %s for reading!\n", readPath);
+ exit(-1);
+ }
+
+ currentPos = -1;
+ if((currentPos = hdfsTell(fs, readFile)) != seekPos) {
+ fprintf(stderr,
+ "Failed to get current file position correctly! Got %" PRId64 "!\n",
+ currentPos);
+ exit(-1);
+ }
+ fprintf(stderr, "Current position: %" PRId64 "\n", currentPos);
+
+ if (!hdfsFileUsesDirectRead(readFile)) {
+ fprintf(stderr, "Direct read support incorrectly not detected "
+ "for HDFS filesystem\n");
+ exit(-1);
+ }
+
+ fprintf(stderr, "Direct read support detected for HDFS\n");
+
+ // Test the direct read path
+ if(hdfsSeek(fs, readFile, 0)) {
+ fprintf(stderr, "Failed to seek %s for reading!\n", readPath);
+ exit(-1);
+ }
+ memset(buffer, 0, sizeof(buffer));
+ num_read_bytes = hdfsRead(fs, readFile, (void*)buffer,
+ sizeof(buffer));
+ if (strncmp(fileContents, buffer, strlen(fileContents)) != 0) {
+ fprintf(stderr, "Failed to read (direct). Expected %s but got %s (%d bytes)\n",
+ fileContents, buffer, num_read_bytes);
+ exit(-1);
+ }
+ fprintf(stderr, "Read (direct) following %d bytes:\n%s\n",
+ num_read_bytes, buffer);
+ if (hdfsSeek(fs, readFile, 0L)) {
+ fprintf(stderr, "Failed to seek to file start!\n");
+ exit(-1);
+ }
+
+ // Disable the direct read path so that we really go through the slow
+ // read path
+ hdfsFileDisableDirectRead(readFile);
+
+ num_read_bytes = hdfsRead(fs, readFile, (void*)buffer,
+ sizeof(buffer));
+ fprintf(stderr, "Read following %d bytes:\n%s\n",
+ num_read_bytes, buffer);
+
+ memset(buffer, 0, strlen(fileContents + 1));
+
+ num_read_bytes = hdfsPread(fs, readFile, 0, (void*)buffer,
+ sizeof(buffer));
+ fprintf(stderr, "Read following %d bytes:\n%s\n",
+ num_read_bytes, buffer);
+
+ hdfsCloseFile(fs, readFile);
+
+ // Test correct behaviour for unsupported filesystems
+ localFile = hdfsOpenFile(lfs, writePath, O_WRONLY|O_CREAT, 0, 0, 0);
+ if(!localFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", writePath);
+ exit(-1);
+ }
+
+ num_written_bytes = hdfsWrite(lfs, localFile, (void*)fileContents,
+ (tSize)(strlen(fileContents) + 1));
+
+ hdfsCloseFile(lfs, localFile);
+ localFile = hdfsOpenFile(lfs, writePath, O_RDONLY, 0, 0, 0);
+
+ if (hdfsFileUsesDirectRead(localFile)) {
+ fprintf(stderr, "Direct read support incorrectly detected for local "
+ "filesystem\n");
+ exit(-1);
+ }
+
+ hdfsCloseFile(lfs, localFile);
+ }
+
+ totalResult = 0;
+ result = 0;
+ {
+ //Generic file-system operations
+
+ fprintf(stderr, "hdfsCopy(remote-local): %s\n", ((result = hdfsCopy(fs, srcPath, lfs, srcPath)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsCopy(remote-remote): %s\n", ((result = hdfsCopy(fs, srcPath, fs, dstPath)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsMove(local-local): %s\n", ((result = hdfsMove(lfs, srcPath, lfs, dstPath)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsMove(remote-local): %s\n", ((result = hdfsMove(fs, srcPath, lfs, srcPath)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+ fprintf(stderr, "hdfsRename: %s\n", ((result = hdfsRename(fs, dstPath, srcPath)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsCopy(remote-remote): %s\n", ((result = hdfsCopy(fs, srcPath, fs, dstPath)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+ fprintf(stderr, "hdfsCreateDirectory: %s\n", ((result = hdfsCreateDirectory(fs, newDirectory)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+ fprintf(stderr, "hdfsSetReplication: %s\n", ((result = hdfsSetReplication(fs, srcPath, 2)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+ fprintf(stderr, "hdfsGetWorkingDirectory: %s\n", ((resp = hdfsGetWorkingDirectory(fs, buffer2, sizeof(buffer2))) != 0 ? buffer2 : "Failed!"));
+ totalResult += (resp ? 0 : 1);
+ fprintf(stderr, "hdfsSetWorkingDirectory: %s\n", ((result = hdfsSetWorkingDirectory(fs, slashTmp)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsGetWorkingDirectory: %s\n", ((resp = hdfsGetWorkingDirectory(fs, buffer2, sizeof(buffer2))) != 0 ? buffer2 : "Failed!"));
+ totalResult += (resp ? 0 : 1);
+
+ fprintf(stderr, "hdfsGetDefaultBlockSize: %" PRId64 "\n", hdfsGetDefaultBlockSize(fs));
+ fprintf(stderr, "hdfsGetCapacity: %" PRId64 "\n", hdfsGetCapacity(fs));
+ fprintf(stderr, "hdfsGetUsed: %" PRId64 "\n", hdfsGetUsed(fs));
+
+ fileInfo = NULL;
+ if((fileInfo = hdfsGetPathInfo(fs, slashTmp)) != NULL) {
+ fprintf(stderr, "hdfsGetPathInfo - SUCCESS!\n");
+ fprintf(stderr, "Name: %s, ", fileInfo->mName);
+ fprintf(stderr, "Type: %c, ", (char)(fileInfo->mKind));
+ fprintf(stderr, "Replication: %d, ", fileInfo->mReplication);
+ fprintf(stderr, "BlockSize: %" PRId64 ", ", fileInfo->mBlockSize);
+ fprintf(stderr, "Size: %" PRId64 ", ", fileInfo->mSize);
+ fprintf(stderr, "LastMod: %s", ctime(&fileInfo->mLastMod));
+ fprintf(stderr, "Owner: %s, ", fileInfo->mOwner);
+ fprintf(stderr, "Group: %s, ", fileInfo->mGroup);
+ permission_disp(fileInfo->mPermissions, permissions);
+ fprintf(stderr, "Permissions: %d (%s)\n", fileInfo->mPermissions, permissions);
+ hdfsFreeFileInfo(fileInfo, 1);
+ } else {
+ totalResult++;
+ fprintf(stderr, "waah! hdfsGetPathInfo for %s - FAILED!\n", slashTmp);
+ }
+
+ fileList = 0;
+ fileList = hdfsListDirectory(fs, newDirectory, &numEntries);
+ if (!(fileList == NULL && numEntries == 0 && !errno)) {
+ fprintf(stderr, "waah! hdfsListDirectory for empty %s - FAILED!\n", newDirectory);
+ totalResult++;
+ } else {
+ fprintf(stderr, "hdfsListDirectory for empty %s - SUCCESS!\n", newDirectory);
+ }
+
+ fileList = 0;
+ if((fileList = hdfsListDirectory(fs, slashTmp, &numEntries)) != NULL) {
+ for(i=0; i < numEntries; ++i) {
+ fprintf(stderr, "Name: %s, ", fileList[i].mName);
+ fprintf(stderr, "Type: %c, ", (char)fileList[i].mKind);
+ fprintf(stderr, "Replication: %d, ", fileList[i].mReplication);
+ fprintf(stderr, "BlockSize: %" PRId64 ", ", fileList[i].mBlockSize);
+ fprintf(stderr, "Size: %" PRId64 ", ", fileList[i].mSize);
+ fprintf(stderr, "LastMod: %s", ctime(&fileList[i].mLastMod));
+ fprintf(stderr, "Owner: %s, ", fileList[i].mOwner);
+ fprintf(stderr, "Group: %s, ", fileList[i].mGroup);
+ permission_disp(fileList[i].mPermissions, permissions);
+ fprintf(stderr, "Permissions: %d (%s)\n", fileList[i].mPermissions, permissions);
+ }
+ hdfsFreeFileInfo(fileList, numEntries);
+ } else {
+ if (errno) {
+ totalResult++;
+ fprintf(stderr, "waah! hdfsListDirectory - FAILED!\n");
+ } else {
+ fprintf(stderr, "Empty directory!\n");
+ }
+ }
+
+ hosts = hdfsGetHosts(fs, srcPath, 0, 1);
+ if(hosts) {
+ fprintf(stderr, "hdfsGetHosts - SUCCESS! ... \n");
+ i=0;
+ while(hosts[i]) {
+ j = 0;
+ while(hosts[i][j]) {
+ fprintf(stderr,
+ "\thosts[%d][%d] - %s\n", i, j, hosts[i][j]);
+ ++j;
+ }
+ ++i;
+ }
+ } else {
+ totalResult++;
+ fprintf(stderr, "waah! hdfsGetHosts - FAILED!\n");
+ }
+
+ // setting tmp dir to 777 so later when connectAsUser nobody, we can write to it
+
+ // chown write
+ fprintf(stderr, "hdfsChown: %s\n", ((result = hdfsChown(fs, writePath, NULL, "users")) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsChown: %s\n", ((result = hdfsChown(fs, writePath, newOwner, NULL)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ // chmod write
+ fprintf(stderr, "hdfsChmod: %s\n", ((result = hdfsChmod(fs, writePath, newPerm)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+
+
+ sleep(2);
+ newMtime = time(NULL);
+ newAtime = time(NULL);
+
+ // utime write
+ fprintf(stderr, "hdfsUtime: %s\n", ((result = hdfsUtime(fs, writePath, newMtime, newAtime)) != 0 ? "Failed!" : "Success!"));
+
+ totalResult += result;
+
+ // chown/chmod/utime read
+ finfo = hdfsGetPathInfo(fs, writePath);
+
+ fprintf(stderr, "hdfsChown read: %s\n", ((result = (strcmp(finfo->mOwner, newOwner))) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+ fprintf(stderr, "hdfsChmod read: %s\n", ((result = (finfo->mPermissions != newPerm)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+ // will later use /tmp/ as a different user so enable it
+ fprintf(stderr, "hdfsChmod: %s\n", ((result = hdfsChmod(fs, "/tmp/", 0777)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+ fprintf(stderr,"newMTime=%ld\n",newMtime);
+ fprintf(stderr,"curMTime=%ld\n",finfo->mLastMod);
+
+
+ fprintf(stderr, "hdfsUtime read (mtime): %s\n", ((result = (finfo->mLastMod != newMtime)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+
+ // No easy way to turn on access times from hdfs_test right now
+ // fprintf(stderr, "hdfsUtime read (atime): %s\n", ((result = (finfo->mLastAccess != newAtime)) != 0 ? "Failed!" : "Success!"));
+ // totalResult += result;
+
+ hdfsFreeFileInfo(finfo, 1);
+
+ // Clean up
+ fprintf(stderr, "hdfsDelete: %s\n", ((result = hdfsDelete(fs, newDirectory, 1)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsDelete: %s\n", ((result = hdfsDelete(fs, srcPath, 1)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsDelete: %s\n", ((result = hdfsDelete(lfs, srcPath, 1)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsDelete: %s\n", ((result = hdfsDelete(lfs, dstPath, 1)) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsExists: %s\n", ((result = hdfsExists(fs, newDirectory)) != 0 ? "Success!" : "Failed!"));
+ totalResult += (result ? 0 : 1);
+ }
+
+ {
+ // TEST APPENDS
+
+ // CREATE
+ appendFile = hdfsOpenFile(fs, appendPath, O_WRONLY, 0, 0, 0);
+ if(!appendFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", appendPath);
+ exit(-1);
+ }
+ fprintf(stderr, "Opened %s for writing successfully...\n", appendPath);
+
+ buffer3 = "Hello,";
+ num_written_bytes = hdfsWrite(fs, appendFile, (void*)buffer3,
+ (tSize)strlen(buffer3));
+ fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
+
+ if (hdfsFlush(fs, appendFile)) {
+ fprintf(stderr, "Failed to 'flush' %s\n", appendPath);
+ exit(-1);
+ }
+ fprintf(stderr, "Flushed %s successfully!\n", appendPath);
+
+ hdfsCloseFile(fs, appendFile);
+
+ // RE-OPEN
+ appendFile = hdfsOpenFile(fs, appendPath, O_WRONLY|O_APPEND, 0, 0, 0);
+ if(!appendFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", appendPath);
+ exit(-1);
+ }
+ fprintf(stderr, "Opened %s for writing successfully...\n", appendPath);
+
+ buffer3 = " World";
+ num_written_bytes = hdfsWrite(fs, appendFile, (void*)buffer3,
+ (tSize)(strlen(buffer3) + 1));
+ fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
+
+ if (hdfsFlush(fs, appendFile)) {
+ fprintf(stderr, "Failed to 'flush' %s\n", appendPath);
+ exit(-1);
+ }
+ fprintf(stderr, "Flushed %s successfully!\n", appendPath);
+
+ hdfsCloseFile(fs, appendFile);
+
+ // CHECK size
+ finfo = hdfsGetPathInfo(fs, appendPath);
+ fprintf(stderr, "fileinfo->mSize: == total %s\n", ((result = (finfo->mSize == (tOffset)(strlen("Hello, World") + 1))) == 1 ? "Success!" : "Failed!"));
+ totalResult += (result ? 0 : 1);
+
+ // READ and check data
+ readFile = hdfsOpenFile(fs, appendPath, O_RDONLY, 0, 0, 0);
+ if (!readFile) {
+ fprintf(stderr, "Failed to open %s for reading!\n", appendPath);
+ exit(-1);
+ }
+
+ num_read_bytes = hdfsRead(fs, readFile, (void*)rdbuffer, sizeof(rdbuffer));
+ fprintf(stderr, "Read following %d bytes:\n%s\n",
+ num_read_bytes, rdbuffer);
+
+ fprintf(stderr, "read == Hello, World %s\n", ((result = (strcmp(rdbuffer, "Hello, World"))) == 0 ? "Success!" : "Failed!"));
+
+ hdfsCloseFile(fs, readFile);
+
+ // DONE test appends
+ }
+
+
+ totalResult += (hdfsDisconnect(fs) != 0);
+
+ {
+ //
+ // Now test as connecting as a specific user
+ // This is only meant to test that we connected as that user, not to test
+ // the actual fs user capabilities. Thus just create a file and read
+ // the owner is correct.
+
+ fs = hdfsConnectAsUserNewInstance("default", 0, tuser);
+ if(!fs) {
+ fprintf(stderr, "Oops! Failed to connect to hdfs as user %s!\n",tuser);
+ exit(-1);
+ }
+
+ userFile = hdfsOpenFile(fs, userPath, O_WRONLY|O_CREAT, 0, 0, 0);
+ if(!userFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", userPath);
+ exit(-1);
+ }
+ fprintf(stderr, "Opened %s for writing successfully...\n", userPath);
+
+ num_written_bytes = hdfsWrite(fs, userFile, (void*)fileContents,
+ (tSize)(strlen(fileContents)+1));
+ fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
+
+ if (hdfsFlush(fs, userFile)) {
+ fprintf(stderr, "Failed to 'flush' %s\n", userPath);
+ exit(-1);
+ }
+ fprintf(stderr, "Flushed %s successfully!\n", userPath);
+
+ hdfsCloseFile(fs, userFile);
+
+ finfo = hdfsGetPathInfo(fs, userPath);
+ fprintf(stderr, "hdfs new file user is correct: %s\n", ((result = (strcmp(finfo->mOwner, tuser))) != 0 ? "Failed!" : "Success!"));
+ totalResult += result;
+ }
+
+ totalResult += (hdfsDisconnect(fs) != 0);
+
+ if (totalResult != 0) {
+ return -1;
+ } else {
+ return 0;
+ }
+}
+
+/**
+ * vim: ts=4: sw=4: et:
+ */
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_read.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_read.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_read.c
new file mode 100644
index 0000000..6e44741
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_read.c
@@ -0,0 +1,72 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "hdfs.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+int main(int argc, char **argv) {
+ hdfsFS fs;
+ const char *rfile = argv[1];
+ tSize bufferSize = strtoul(argv[3], NULL, 10);
+ hdfsFile readFile;
+ char* buffer;
+ tSize curSize;
+
+ if (argc != 4) {
+ fprintf(stderr, "Usage: hdfs_read <filename> <filesize> <buffersize>\n");
+ exit(-1);
+ }
+
+ fs = hdfsConnect("default", 0);
+ if (!fs) {
+ fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
+ exit(-1);
+ }
+
+ readFile = hdfsOpenFile(fs, rfile, O_RDONLY, bufferSize, 0, 0);
+ if (!readFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", rfile);
+ exit(-2);
+ }
+
+ // data to be written to the file
+ buffer = malloc(sizeof(char) * bufferSize);
+ if(buffer == NULL) {
+ return -2;
+ }
+
+ // read from the file
+ curSize = bufferSize;
+ for (; curSize == bufferSize;) {
+ curSize = hdfsRead(fs, readFile, (void*)buffer, curSize);
+ }
+
+
+ free(buffer);
+ hdfsCloseFile(fs, readFile);
+ hdfsDisconnect(fs);
+
+ return 0;
+}
+
+/**
+ * vim: ts=4: sw=4: et:
+ */
+
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_write.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_write.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_write.c
new file mode 100644
index 0000000..42b3df7
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_write.c
@@ -0,0 +1,99 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "hdfs.h"
+
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+
+int main(int argc, char **argv) {
+ hdfsFS fs;
+ const char *writeFileName = argv[1];
+ off_t fileTotalSize = strtoul(argv[2], NULL, 10);
+ long long tmpBufferSize = strtoul(argv[3], NULL, 10);
+ tSize bufferSize;
+ hdfsFile writeFile;
+ char* buffer;
+ int i;
+ off_t nrRemaining;
+ tSize curSize;
+ tSize written;
+
+ if (argc != 4) {
+ fprintf(stderr, "Usage: hdfs_write <filename> <filesize> <buffersize>\n");
+ exit(-1);
+ }
+
+ fs = hdfsConnect("default", 0);
+ if (!fs) {
+ fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
+ exit(-1);
+ }
+
+ // sanity check
+ if(fileTotalSize == ULONG_MAX && errno == ERANGE) {
+ fprintf(stderr, "invalid file size %s - must be <= %lu\n", argv[2], ULONG_MAX);
+ exit(-3);
+ }
+
+ // currently libhdfs writes are of tSize which is int32
+ if(tmpBufferSize > INT_MAX) {
+ fprintf(stderr, "invalid buffer size libhdfs API write chunks must be <= %d\n",INT_MAX);
+ exit(-3);
+ }
+
+ bufferSize = (tSize)tmpBufferSize;
+
+ writeFile = hdfsOpenFile(fs, writeFileName, O_WRONLY, bufferSize, 0, 0);
+ if (!writeFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", writeFileName);
+ exit(-2);
+ }
+
+ // data to be written to the file
+ buffer = malloc(sizeof(char) * bufferSize);
+ if(buffer == NULL) {
+ fprintf(stderr, "Could not allocate buffer of size %d\n", bufferSize);
+ return -2;
+ }
+ for (i=0; i < bufferSize; ++i) {
+ buffer[i] = 'a' + (i%26);
+ }
+
+ // write to the file
+ for (nrRemaining = fileTotalSize; nrRemaining > 0; nrRemaining -= bufferSize ) {
+ curSize = ( bufferSize < nrRemaining ) ? bufferSize : (tSize)nrRemaining;
+ if ((written = hdfsWrite(fs, writeFile, (void*)buffer, curSize)) != curSize) {
+ fprintf(stderr, "ERROR: hdfsWrite returned an error on write: %d\n", written);
+ exit(-3);
+ }
+ }
+
+ free(buffer);
+ hdfsCloseFile(fs, writeFile);
+ hdfsDisconnect(fs);
+
+ return 0;
+}
+
+/**
+ * vim: ts=4: sw=4: et:
+ */
+
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_zerocopy.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_zerocopy.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_zerocopy.c
new file mode 100644
index 0000000..92941cf
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/test/test_libhdfs_zerocopy.c
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "expect.h"
+#include "hdfs.h"
+#include "native_mini_dfs.h"
+#include "platform.h"
+
+#include <errno.h>
+#include <inttypes.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+
+#define TO_STR_HELPER(X) #X
+#define TO_STR(X) TO_STR_HELPER(X)
+
+#define TEST_FILE_NAME_LENGTH 128
+#define TEST_ZEROCOPY_FULL_BLOCK_SIZE 4096
+#define TEST_ZEROCOPY_LAST_BLOCK_SIZE 3215
+#define TEST_ZEROCOPY_NUM_BLOCKS 6
+#define SMALL_READ_LEN 16
+#define TEST_ZEROCOPY_FILE_LEN \
+ (((TEST_ZEROCOPY_NUM_BLOCKS - 1) * TEST_ZEROCOPY_FULL_BLOCK_SIZE) + \
+ TEST_ZEROCOPY_LAST_BLOCK_SIZE)
+
+#define ZC_BUF_LEN 32768
+
+static uint8_t *getZeroCopyBlockData(int blockIdx)
+{
+ uint8_t *buf = malloc(TEST_ZEROCOPY_FULL_BLOCK_SIZE);
+ int i;
+ if (!buf) {
+ fprintf(stderr, "malloc(%d) failed\n", TEST_ZEROCOPY_FULL_BLOCK_SIZE);
+ exit(1);
+ }
+ for (i = 0; i < TEST_ZEROCOPY_FULL_BLOCK_SIZE; i++) {
+ buf[i] = (uint8_t)(blockIdx + (i % 17));
+ }
+ return buf;
+}
+
+static int getZeroCopyBlockLen(int blockIdx)
+{
+ if (blockIdx >= TEST_ZEROCOPY_NUM_BLOCKS) {
+ return 0;
+ } else if (blockIdx == (TEST_ZEROCOPY_NUM_BLOCKS - 1)) {
+ return TEST_ZEROCOPY_LAST_BLOCK_SIZE;
+ } else {
+ return TEST_ZEROCOPY_FULL_BLOCK_SIZE;
+ }
+}
+
+static int doTestZeroCopyReads(hdfsFS fs, const char *fileName)
+{
+ hdfsFile file = NULL;
+ struct hadoopRzOptions *opts = NULL;
+ struct hadoopRzBuffer *buffer = NULL;
+ uint8_t *block;
+
+ file = hdfsOpenFile(fs, fileName, O_RDONLY, 0, 0, 0);
+ EXPECT_NONNULL(file);
+ opts = hadoopRzOptionsAlloc();
+ EXPECT_NONNULL(opts);
+ EXPECT_ZERO(hadoopRzOptionsSetSkipChecksum(opts, 1));
+ /* haven't read anything yet */
+ EXPECT_ZERO(expectFileStats(file, 0LL, 0LL, 0LL, 0LL));
+ block = getZeroCopyBlockData(0);
+ EXPECT_NONNULL(block);
+ /* first read is half of a block. */
+ buffer = hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2);
+ EXPECT_NONNULL(buffer);
+ EXPECT_INT_EQ(TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2,
+ hadoopRzBufferLength(buffer));
+ EXPECT_ZERO(memcmp(hadoopRzBufferGet(buffer), block,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2));
+ hadoopRzBufferFree(file, buffer);
+ /* read the next half of the block */
+ buffer = hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2);
+ EXPECT_NONNULL(buffer);
+ EXPECT_INT_EQ(TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2,
+ hadoopRzBufferLength(buffer));
+ EXPECT_ZERO(memcmp(hadoopRzBufferGet(buffer),
+ block + (TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2),
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2));
+ hadoopRzBufferFree(file, buffer);
+ free(block);
+ EXPECT_ZERO(expectFileStats(file, TEST_ZEROCOPY_FULL_BLOCK_SIZE,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE));
+ /* Now let's read just a few bytes. */
+ buffer = hadoopReadZero(file, opts, SMALL_READ_LEN);
+ EXPECT_NONNULL(buffer);
+ EXPECT_INT_EQ(SMALL_READ_LEN, hadoopRzBufferLength(buffer));
+ block = getZeroCopyBlockData(1);
+ EXPECT_NONNULL(block);
+ EXPECT_ZERO(memcmp(block, hadoopRzBufferGet(buffer), SMALL_READ_LEN));
+ hadoopRzBufferFree(file, buffer);
+ EXPECT_INT64_EQ(
+ (int64_t)TEST_ZEROCOPY_FULL_BLOCK_SIZE + (int64_t)SMALL_READ_LEN,
+ hdfsTell(fs, file));
+ EXPECT_ZERO(expectFileStats(file,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN));
+
+ /* Clear 'skip checksums' and test that we can't do zero-copy reads any
+ * more. Since there is no ByteBufferPool set, we should fail with
+ * EPROTONOSUPPORT.
+ */
+ EXPECT_ZERO(hadoopRzOptionsSetSkipChecksum(opts, 0));
+ EXPECT_NULL(hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE));
+ EXPECT_INT_EQ(EPROTONOSUPPORT, errno);
+
+ /* Verify that setting a NULL ByteBufferPool class works. */
+ EXPECT_ZERO(hadoopRzOptionsSetByteBufferPool(opts, NULL));
+ EXPECT_ZERO(hadoopRzOptionsSetSkipChecksum(opts, 0));
+ EXPECT_NULL(hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE));
+ EXPECT_INT_EQ(EPROTONOSUPPORT, errno);
+
+ /* Now set a ByteBufferPool and try again. It should succeed this time. */
+ EXPECT_ZERO(hadoopRzOptionsSetByteBufferPool(opts,
+ ELASTIC_BYTE_BUFFER_POOL_CLASS));
+ buffer = hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE);
+ EXPECT_NONNULL(buffer);
+ EXPECT_INT_EQ(TEST_ZEROCOPY_FULL_BLOCK_SIZE, hadoopRzBufferLength(buffer));
+ EXPECT_ZERO(expectFileStats(file,
+ (2 * TEST_ZEROCOPY_FULL_BLOCK_SIZE) + SMALL_READ_LEN,
+ (2 * TEST_ZEROCOPY_FULL_BLOCK_SIZE) + SMALL_READ_LEN,
+ (2 * TEST_ZEROCOPY_FULL_BLOCK_SIZE) + SMALL_READ_LEN,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN));
+ EXPECT_ZERO(memcmp(block + SMALL_READ_LEN, hadoopRzBufferGet(buffer),
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE - SMALL_READ_LEN));
+ free(block);
+ block = getZeroCopyBlockData(2);
+ EXPECT_NONNULL(block);
+ EXPECT_ZERO(memcmp(block, (uint8_t*)hadoopRzBufferGet(buffer) +
+ (TEST_ZEROCOPY_FULL_BLOCK_SIZE - SMALL_READ_LEN), SMALL_READ_LEN));
+ hadoopRzBufferFree(file, buffer);
+
+ /* Check the result of a zero-length read. */
+ buffer = hadoopReadZero(file, opts, 0);
+ EXPECT_NONNULL(buffer);
+ EXPECT_NONNULL(hadoopRzBufferGet(buffer));
+ EXPECT_INT_EQ(0, hadoopRzBufferLength(buffer));
+ hadoopRzBufferFree(file, buffer);
+
+ /* Check the result of reading past EOF */
+ EXPECT_INT_EQ(0, hdfsSeek(fs, file, TEST_ZEROCOPY_FILE_LEN));
+ buffer = hadoopReadZero(file, opts, 1);
+ EXPECT_NONNULL(buffer);
+ EXPECT_NULL(hadoopRzBufferGet(buffer));
+ hadoopRzBufferFree(file, buffer);
+
+ /* Cleanup */
+ free(block);
+ hadoopRzOptionsFree(opts);
+ EXPECT_ZERO(hdfsCloseFile(fs, file));
+ return 0;
+}
+
+static int createZeroCopyTestFile(hdfsFS fs, char *testFileName,
+ size_t testFileNameLen)
+{
+ int blockIdx, blockLen;
+ hdfsFile file;
+ uint8_t *data;
+
+ snprintf(testFileName, testFileNameLen, "/zeroCopyTestFile.%d.%d",
+ getpid(), rand());
+ file = hdfsOpenFile(fs, testFileName, O_WRONLY, 0, 1,
+ TEST_ZEROCOPY_FULL_BLOCK_SIZE);
+ EXPECT_NONNULL(file);
+ for (blockIdx = 0; blockIdx < TEST_ZEROCOPY_NUM_BLOCKS; blockIdx++) {
+ blockLen = getZeroCopyBlockLen(blockIdx);
+ data = getZeroCopyBlockData(blockIdx);
+ EXPECT_NONNULL(data);
+ EXPECT_INT_EQ(blockLen, hdfsWrite(fs, file, data, blockLen));
+ }
+ EXPECT_ZERO(hdfsCloseFile(fs, file));
+ return 0;
+}
+
+static int nmdConfigureHdfsBuilder(struct NativeMiniDfsCluster *cl,
+ struct hdfsBuilder *bld) {
+ int ret;
+ tPort port;
+ const char *domainSocket;
+
+ hdfsBuilderSetNameNode(bld, "localhost");
+ port = (tPort) nmdGetNameNodePort(cl);
+ if (port < 0) {
+ fprintf(stderr, "nmdGetNameNodePort failed with error %d\n", -port);
+ return EIO;
+ }
+ hdfsBuilderSetNameNodePort(bld, port);
+
+ domainSocket = hdfsGetDomainSocketPath(cl);
+
+ if (domainSocket) {
+ ret = hdfsBuilderConfSetStr(bld, "dfs.client.read.shortcircuit", "true");
+ if (ret) {
+ return ret;
+ }
+ ret = hdfsBuilderConfSetStr(bld, "dfs.domain.socket.path",
+ domainSocket);
+ if (ret) {
+ return ret;
+ }
+ }
+ return 0;
+}
+
+
+/**
+ * Test that we can write a file with libhdfs and then read it back
+ */
+int main(void)
+{
+ int port;
+ struct NativeMiniDfsConf conf = {
+ 1, /* doFormat */
+ 0, /* webhdfsEnabled */
+ 0, /* namenodeHttpPort */
+ 1, /* configureShortCircuit */
+ };
+ char testFileName[TEST_FILE_NAME_LENGTH];
+ hdfsFS fs;
+ struct NativeMiniDfsCluster* cl;
+ struct hdfsBuilder *bld;
+
+ cl = nmdCreate(&conf);
+ EXPECT_NONNULL(cl);
+ EXPECT_ZERO(nmdWaitClusterUp(cl));
+ port = nmdGetNameNodePort(cl);
+ if (port < 0) {
+ fprintf(stderr, "TEST_ERROR: test_zerocopy: "
+ "nmdGetNameNodePort returned error %d\n", port);
+ return EXIT_FAILURE;
+ }
+ bld = hdfsNewBuilder();
+ EXPECT_NONNULL(bld);
+ EXPECT_ZERO(nmdConfigureHdfsBuilder(cl, bld));
+ hdfsBuilderSetForceNewInstance(bld);
+ hdfsBuilderConfSetStr(bld, "dfs.block.size",
+ TO_STR(TEST_ZEROCOPY_FULL_BLOCK_SIZE));
+ /* ensure that we'll always get our mmaps */
+ hdfsBuilderConfSetStr(bld, "dfs.client.read.shortcircuit.skip.checksum",
+ "true");
+ fs = hdfsBuilderConnect(bld);
+ EXPECT_NONNULL(fs);
+ EXPECT_ZERO(createZeroCopyTestFile(fs, testFileName,
+ TEST_FILE_NAME_LENGTH));
+ EXPECT_ZERO(doTestZeroCopyReads(fs, testFileName));
+ EXPECT_ZERO(hdfsDisconnect(fs));
+ EXPECT_ZERO(nmdShutdown(cl));
+ nmdFree(cl);
+ fprintf(stderr, "TEST_SUCCESS\n");
+ return EXIT_SUCCESS;
+}
[18/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs.c
new file mode 100644
index 0000000..a3769fc
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs.c
@@ -0,0 +1,3342 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "exception.h"
+#include "hdfs.h"
+#include "jni_helper.h"
+#include "platform.h"
+
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+
+/* Some frequently used Java paths */
+#define HADOOP_CONF "org/apache/hadoop/conf/Configuration"
+#define HADOOP_PATH "org/apache/hadoop/fs/Path"
+#define HADOOP_LOCALFS "org/apache/hadoop/fs/LocalFileSystem"
+#define HADOOP_FS "org/apache/hadoop/fs/FileSystem"
+#define HADOOP_FSSTATUS "org/apache/hadoop/fs/FsStatus"
+#define HADOOP_BLK_LOC "org/apache/hadoop/fs/BlockLocation"
+#define HADOOP_DFS "org/apache/hadoop/hdfs/DistributedFileSystem"
+#define HADOOP_ISTRM "org/apache/hadoop/fs/FSDataInputStream"
+#define HADOOP_OSTRM "org/apache/hadoop/fs/FSDataOutputStream"
+#define HADOOP_STAT "org/apache/hadoop/fs/FileStatus"
+#define HADOOP_FSPERM "org/apache/hadoop/fs/permission/FsPermission"
+#define JAVA_NET_ISA "java/net/InetSocketAddress"
+#define JAVA_NET_URI "java/net/URI"
+#define JAVA_STRING "java/lang/String"
+#define READ_OPTION "org/apache/hadoop/fs/ReadOption"
+
+#define JAVA_VOID "V"
+
+/* Macros for constructing method signatures */
+#define JPARAM(X) "L" X ";"
+#define JARRPARAM(X) "[L" X ";"
+#define JMETHOD1(X, R) "(" X ")" R
+#define JMETHOD2(X, Y, R) "(" X Y ")" R
+#define JMETHOD3(X, Y, Z, R) "(" X Y Z")" R
+
+#define KERBEROS_TICKET_CACHE_PATH "hadoop.security.kerberos.ticket.cache.path"
+
+// Bit fields for hdfsFile_internal flags
+#define HDFS_FILE_SUPPORTS_DIRECT_READ (1<<0)
+
+tSize readDirect(hdfsFS fs, hdfsFile f, void* buffer, tSize length);
+static void hdfsFreeFileInfoEntry(hdfsFileInfo *hdfsFileInfo);
+
+/**
+ * The C equivalent of org.apache.org.hadoop.FSData(Input|Output)Stream .
+ */
+enum hdfsStreamType
+{
+ HDFS_STREAM_UNINITIALIZED = 0,
+ HDFS_STREAM_INPUT = 1,
+ HDFS_STREAM_OUTPUT = 2,
+};
+
+/**
+ * The 'file-handle' to a file in hdfs.
+ */
+struct hdfsFile_internal {
+ void* file;
+ enum hdfsStreamType type;
+ int flags;
+};
+
+#define HDFS_EXTENDED_FILE_INFO_ENCRYPTED 0x1
+
+/**
+ * Extended file information.
+ */
+struct hdfsExtendedFileInfo {
+ int flags;
+};
+
+int hdfsFileIsOpenForRead(hdfsFile file)
+{
+ return (file->type == HDFS_STREAM_INPUT);
+}
+
+int hdfsFileGetReadStatistics(hdfsFile file,
+ struct hdfsReadStatistics **stats)
+{
+ jthrowable jthr;
+ jobject readStats = NULL;
+ jvalue jVal;
+ struct hdfsReadStatistics *s = NULL;
+ int ret;
+ JNIEnv* env = getJNIEnv();
+
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+ if (file->type != HDFS_STREAM_INPUT) {
+ ret = EINVAL;
+ goto done;
+ }
+ jthr = invokeMethod(env, &jVal, INSTANCE, file->file,
+ "org/apache/hadoop/hdfs/client/HdfsDataInputStream",
+ "getReadStatistics",
+ "()Lorg/apache/hadoop/hdfs/DFSInputStream$ReadStatistics;");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsFileGetReadStatistics: getReadStatistics failed");
+ goto done;
+ }
+ readStats = jVal.l;
+ s = malloc(sizeof(struct hdfsReadStatistics));
+ if (!s) {
+ ret = ENOMEM;
+ goto done;
+ }
+ jthr = invokeMethod(env, &jVal, INSTANCE, readStats,
+ "org/apache/hadoop/hdfs/DFSInputStream$ReadStatistics",
+ "getTotalBytesRead", "()J");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsFileGetReadStatistics: getTotalBytesRead failed");
+ goto done;
+ }
+ s->totalBytesRead = jVal.j;
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, readStats,
+ "org/apache/hadoop/hdfs/DFSInputStream$ReadStatistics",
+ "getTotalLocalBytesRead", "()J");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsFileGetReadStatistics: getTotalLocalBytesRead failed");
+ goto done;
+ }
+ s->totalLocalBytesRead = jVal.j;
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, readStats,
+ "org/apache/hadoop/hdfs/DFSInputStream$ReadStatistics",
+ "getTotalShortCircuitBytesRead", "()J");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsFileGetReadStatistics: getTotalShortCircuitBytesRead failed");
+ goto done;
+ }
+ s->totalShortCircuitBytesRead = jVal.j;
+ jthr = invokeMethod(env, &jVal, INSTANCE, readStats,
+ "org/apache/hadoop/hdfs/DFSInputStream$ReadStatistics",
+ "getTotalZeroCopyBytesRead", "()J");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsFileGetReadStatistics: getTotalZeroCopyBytesRead failed");
+ goto done;
+ }
+ s->totalZeroCopyBytesRead = jVal.j;
+ *stats = s;
+ s = NULL;
+ ret = 0;
+
+done:
+ destroyLocalReference(env, readStats);
+ free(s);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int64_t hdfsReadStatisticsGetRemoteBytesRead(
+ const struct hdfsReadStatistics *stats)
+{
+ return stats->totalBytesRead - stats->totalLocalBytesRead;
+}
+
+int hdfsFileClearReadStatistics(hdfsFile file)
+{
+ jthrowable jthr;
+ int ret;
+ JNIEnv* env = getJNIEnv();
+
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return EINTERNAL;
+ }
+ if (file->type != HDFS_STREAM_INPUT) {
+ ret = EINVAL;
+ goto done;
+ }
+ jthr = invokeMethod(env, NULL, INSTANCE, file->file,
+ "org/apache/hadoop/hdfs/client/HdfsDataInputStream",
+ "clearReadStatistics", "()V");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsFileClearReadStatistics: clearReadStatistics failed");
+ goto done;
+ }
+ ret = 0;
+done:
+ if (ret) {
+ errno = ret;
+ return ret;
+ }
+ return 0;
+}
+
+void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats)
+{
+ free(stats);
+}
+
+int hdfsFileIsOpenForWrite(hdfsFile file)
+{
+ return (file->type == HDFS_STREAM_OUTPUT);
+}
+
+int hdfsFileUsesDirectRead(hdfsFile file)
+{
+ return !!(file->flags & HDFS_FILE_SUPPORTS_DIRECT_READ);
+}
+
+void hdfsFileDisableDirectRead(hdfsFile file)
+{
+ file->flags &= ~HDFS_FILE_SUPPORTS_DIRECT_READ;
+}
+
+int hdfsDisableDomainSocketSecurity(void)
+{
+ jthrowable jthr;
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+ jthr = invokeMethod(env, NULL, STATIC, NULL,
+ "org/apache/hadoop/net/unix/DomainSocket",
+ "disableBindPathValidation", "()V");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "DomainSocket#disableBindPathValidation");
+ return -1;
+ }
+ return 0;
+}
+
+/**
+ * hdfsJniEnv: A wrapper struct to be used as 'value'
+ * while saving thread -> JNIEnv* mappings
+ */
+typedef struct
+{
+ JNIEnv* env;
+} hdfsJniEnv;
+
+/**
+ * Helper function to create a org.apache.hadoop.fs.Path object.
+ * @param env: The JNIEnv pointer.
+ * @param path: The file-path for which to construct org.apache.hadoop.fs.Path
+ * object.
+ * @return Returns a jobject on success and NULL on error.
+ */
+static jthrowable constructNewObjectOfPath(JNIEnv *env, const char *path,
+ jobject *out)
+{
+ jthrowable jthr;
+ jstring jPathString;
+ jobject jPath;
+
+ //Construct a java.lang.String object
+ jthr = newJavaStr(env, path, &jPathString);
+ if (jthr)
+ return jthr;
+ //Construct the org.apache.hadoop.fs.Path object
+ jthr = constructNewObjectOfClass(env, &jPath, "org/apache/hadoop/fs/Path",
+ "(Ljava/lang/String;)V", jPathString);
+ destroyLocalReference(env, jPathString);
+ if (jthr)
+ return jthr;
+ *out = jPath;
+ return NULL;
+}
+
+static jthrowable hadoopConfGetStr(JNIEnv *env, jobject jConfiguration,
+ const char *key, char **val)
+{
+ jthrowable jthr;
+ jvalue jVal;
+ jstring jkey = NULL, jRet = NULL;
+
+ jthr = newJavaStr(env, key, &jkey);
+ if (jthr)
+ goto done;
+ jthr = invokeMethod(env, &jVal, INSTANCE, jConfiguration,
+ HADOOP_CONF, "get", JMETHOD1(JPARAM(JAVA_STRING),
+ JPARAM(JAVA_STRING)), jkey);
+ if (jthr)
+ goto done;
+ jRet = jVal.l;
+ jthr = newCStr(env, jRet, val);
+done:
+ destroyLocalReference(env, jkey);
+ destroyLocalReference(env, jRet);
+ return jthr;
+}
+
+int hdfsConfGetStr(const char *key, char **val)
+{
+ JNIEnv *env;
+ int ret;
+ jthrowable jthr;
+ jobject jConfiguration = NULL;
+
+ env = getJNIEnv();
+ if (env == NULL) {
+ ret = EINTERNAL;
+ goto done;
+ }
+ jthr = constructNewObjectOfClass(env, &jConfiguration, HADOOP_CONF, "()V");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsConfGetStr(%s): new Configuration", key);
+ goto done;
+ }
+ jthr = hadoopConfGetStr(env, jConfiguration, key, val);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsConfGetStr(%s): hadoopConfGetStr", key);
+ goto done;
+ }
+ ret = 0;
+done:
+ destroyLocalReference(env, jConfiguration);
+ if (ret)
+ errno = ret;
+ return ret;
+}
+
+void hdfsConfStrFree(char *val)
+{
+ free(val);
+}
+
+static jthrowable hadoopConfGetInt(JNIEnv *env, jobject jConfiguration,
+ const char *key, int32_t *val)
+{
+ jthrowable jthr = NULL;
+ jvalue jVal;
+ jstring jkey = NULL;
+
+ jthr = newJavaStr(env, key, &jkey);
+ if (jthr)
+ return jthr;
+ jthr = invokeMethod(env, &jVal, INSTANCE, jConfiguration,
+ HADOOP_CONF, "getInt", JMETHOD2(JPARAM(JAVA_STRING), "I", "I"),
+ jkey, (jint)(*val));
+ destroyLocalReference(env, jkey);
+ if (jthr)
+ return jthr;
+ *val = jVal.i;
+ return NULL;
+}
+
+int hdfsConfGetInt(const char *key, int32_t *val)
+{
+ JNIEnv *env;
+ int ret;
+ jobject jConfiguration = NULL;
+ jthrowable jthr;
+
+ env = getJNIEnv();
+ if (env == NULL) {
+ ret = EINTERNAL;
+ goto done;
+ }
+ jthr = constructNewObjectOfClass(env, &jConfiguration, HADOOP_CONF, "()V");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsConfGetInt(%s): new Configuration", key);
+ goto done;
+ }
+ jthr = hadoopConfGetInt(env, jConfiguration, key, val);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsConfGetInt(%s): hadoopConfGetInt", key);
+ goto done;
+ }
+ ret = 0;
+done:
+ destroyLocalReference(env, jConfiguration);
+ if (ret)
+ errno = ret;
+ return ret;
+}
+
+struct hdfsBuilderConfOpt {
+ struct hdfsBuilderConfOpt *next;
+ const char *key;
+ const char *val;
+};
+
+struct hdfsBuilder {
+ int forceNewInstance;
+ const char *nn;
+ tPort port;
+ const char *kerbTicketCachePath;
+ const char *userName;
+ struct hdfsBuilderConfOpt *opts;
+};
+
+struct hdfsBuilder *hdfsNewBuilder(void)
+{
+ struct hdfsBuilder *bld = calloc(1, sizeof(struct hdfsBuilder));
+ if (!bld) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ return bld;
+}
+
+int hdfsBuilderConfSetStr(struct hdfsBuilder *bld, const char *key,
+ const char *val)
+{
+ struct hdfsBuilderConfOpt *opt, *next;
+
+ opt = calloc(1, sizeof(struct hdfsBuilderConfOpt));
+ if (!opt)
+ return -ENOMEM;
+ next = bld->opts;
+ bld->opts = opt;
+ opt->next = next;
+ opt->key = key;
+ opt->val = val;
+ return 0;
+}
+
+void hdfsFreeBuilder(struct hdfsBuilder *bld)
+{
+ struct hdfsBuilderConfOpt *cur, *next;
+
+ cur = bld->opts;
+ for (cur = bld->opts; cur; ) {
+ next = cur->next;
+ free(cur);
+ cur = next;
+ }
+ free(bld);
+}
+
+void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld)
+{
+ bld->forceNewInstance = 1;
+}
+
+void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn)
+{
+ bld->nn = nn;
+}
+
+void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port)
+{
+ bld->port = port;
+}
+
+void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName)
+{
+ bld->userName = userName;
+}
+
+void hdfsBuilderSetKerbTicketCachePath(struct hdfsBuilder *bld,
+ const char *kerbTicketCachePath)
+{
+ bld->kerbTicketCachePath = kerbTicketCachePath;
+}
+
+hdfsFS hdfsConnect(const char *host, tPort port)
+{
+ struct hdfsBuilder *bld = hdfsNewBuilder();
+ if (!bld)
+ return NULL;
+ hdfsBuilderSetNameNode(bld, host);
+ hdfsBuilderSetNameNodePort(bld, port);
+ return hdfsBuilderConnect(bld);
+}
+
+/** Always return a new FileSystem handle */
+hdfsFS hdfsConnectNewInstance(const char *host, tPort port)
+{
+ struct hdfsBuilder *bld = hdfsNewBuilder();
+ if (!bld)
+ return NULL;
+ hdfsBuilderSetNameNode(bld, host);
+ hdfsBuilderSetNameNodePort(bld, port);
+ hdfsBuilderSetForceNewInstance(bld);
+ return hdfsBuilderConnect(bld);
+}
+
+hdfsFS hdfsConnectAsUser(const char *host, tPort port, const char *user)
+{
+ struct hdfsBuilder *bld = hdfsNewBuilder();
+ if (!bld)
+ return NULL;
+ hdfsBuilderSetNameNode(bld, host);
+ hdfsBuilderSetNameNodePort(bld, port);
+ hdfsBuilderSetUserName(bld, user);
+ return hdfsBuilderConnect(bld);
+}
+
+/** Always return a new FileSystem handle */
+hdfsFS hdfsConnectAsUserNewInstance(const char *host, tPort port,
+ const char *user)
+{
+ struct hdfsBuilder *bld = hdfsNewBuilder();
+ if (!bld)
+ return NULL;
+ hdfsBuilderSetNameNode(bld, host);
+ hdfsBuilderSetNameNodePort(bld, port);
+ hdfsBuilderSetForceNewInstance(bld);
+ hdfsBuilderSetUserName(bld, user);
+ return hdfsBuilderConnect(bld);
+}
+
+
+/**
+ * Calculate the effective URI to use, given a builder configuration.
+ *
+ * If there is not already a URI scheme, we prepend 'hdfs://'.
+ *
+ * If there is not already a port specified, and a port was given to the
+ * builder, we suffix that port. If there is a port specified but also one in
+ * the URI, that is an error.
+ *
+ * @param bld The hdfs builder object
+ * @param uri (out param) dynamically allocated string representing the
+ * effective URI
+ *
+ * @return 0 on success; error code otherwise
+ */
+static int calcEffectiveURI(struct hdfsBuilder *bld, char ** uri)
+{
+ const char *scheme;
+ char suffix[64];
+ const char *lastColon;
+ char *u;
+ size_t uriLen;
+
+ if (!bld->nn)
+ return EINVAL;
+ scheme = (strstr(bld->nn, "://")) ? "" : "hdfs://";
+ if (bld->port == 0) {
+ suffix[0] = '\0';
+ } else {
+ lastColon = strrchr(bld->nn, ':');
+ if (lastColon && (strspn(lastColon + 1, "0123456789") ==
+ strlen(lastColon + 1))) {
+ fprintf(stderr, "port %d was given, but URI '%s' already "
+ "contains a port!\n", bld->port, bld->nn);
+ return EINVAL;
+ }
+ snprintf(suffix, sizeof(suffix), ":%d", bld->port);
+ }
+
+ uriLen = strlen(scheme) + strlen(bld->nn) + strlen(suffix);
+ u = malloc((uriLen + 1) * (sizeof(char)));
+ if (!u) {
+ fprintf(stderr, "calcEffectiveURI: out of memory");
+ return ENOMEM;
+ }
+ snprintf(u, uriLen + 1, "%s%s%s", scheme, bld->nn, suffix);
+ *uri = u;
+ return 0;
+}
+
+static const char *maybeNull(const char *str)
+{
+ return str ? str : "(NULL)";
+}
+
+static const char *hdfsBuilderToStr(const struct hdfsBuilder *bld,
+ char *buf, size_t bufLen)
+{
+ snprintf(buf, bufLen, "forceNewInstance=%d, nn=%s, port=%d, "
+ "kerbTicketCachePath=%s, userName=%s",
+ bld->forceNewInstance, maybeNull(bld->nn), bld->port,
+ maybeNull(bld->kerbTicketCachePath), maybeNull(bld->userName));
+ return buf;
+}
+
+hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld)
+{
+ JNIEnv *env = 0;
+ jobject jConfiguration = NULL, jFS = NULL, jURI = NULL, jCachePath = NULL;
+ jstring jURIString = NULL, jUserString = NULL;
+ jvalue jVal;
+ jthrowable jthr = NULL;
+ char *cURI = 0, buf[512];
+ int ret;
+ jobject jRet = NULL;
+ struct hdfsBuilderConfOpt *opt;
+
+ //Get the JNIEnv* corresponding to current thread
+ env = getJNIEnv();
+ if (env == NULL) {
+ ret = EINTERNAL;
+ goto done;
+ }
+
+ // jConfiguration = new Configuration();
+ jthr = constructNewObjectOfClass(env, &jConfiguration, HADOOP_CONF, "()V");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)", hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ // set configuration values
+ for (opt = bld->opts; opt; opt = opt->next) {
+ jthr = hadoopConfSetStr(env, jConfiguration, opt->key, opt->val);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s): error setting conf '%s' to '%s'",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)), opt->key, opt->val);
+ goto done;
+ }
+ }
+
+ //Check what type of FileSystem the caller wants...
+ if (bld->nn == NULL) {
+ // Get a local filesystem.
+ if (bld->forceNewInstance) {
+ // fs = FileSytem#newInstanceLocal(conf);
+ jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS,
+ "newInstanceLocal", JMETHOD1(JPARAM(HADOOP_CONF),
+ JPARAM(HADOOP_LOCALFS)), jConfiguration);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jFS = jVal.l;
+ } else {
+ // fs = FileSytem#getLocal(conf);
+ jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS, "getLocal",
+ JMETHOD1(JPARAM(HADOOP_CONF),
+ JPARAM(HADOOP_LOCALFS)),
+ jConfiguration);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jFS = jVal.l;
+ }
+ } else {
+ if (!strcmp(bld->nn, "default")) {
+ // jURI = FileSystem.getDefaultUri(conf)
+ jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS,
+ "getDefaultUri",
+ "(Lorg/apache/hadoop/conf/Configuration;)Ljava/net/URI;",
+ jConfiguration);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jURI = jVal.l;
+ } else {
+ // fs = FileSystem#get(URI, conf, ugi);
+ ret = calcEffectiveURI(bld, &cURI);
+ if (ret)
+ goto done;
+ jthr = newJavaStr(env, cURI, &jURIString);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jthr = invokeMethod(env, &jVal, STATIC, NULL, JAVA_NET_URI,
+ "create", "(Ljava/lang/String;)Ljava/net/URI;",
+ jURIString);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jURI = jVal.l;
+ }
+
+ if (bld->kerbTicketCachePath) {
+ jthr = hadoopConfSetStr(env, jConfiguration,
+ KERBEROS_TICKET_CACHE_PATH, bld->kerbTicketCachePath);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ }
+ jthr = newJavaStr(env, bld->userName, &jUserString);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ if (bld->forceNewInstance) {
+ jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS,
+ "newInstance", JMETHOD3(JPARAM(JAVA_NET_URI),
+ JPARAM(HADOOP_CONF), JPARAM(JAVA_STRING),
+ JPARAM(HADOOP_FS)),
+ jURI, jConfiguration, jUserString);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jFS = jVal.l;
+ } else {
+ jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS, "get",
+ JMETHOD3(JPARAM(JAVA_NET_URI), JPARAM(HADOOP_CONF),
+ JPARAM(JAVA_STRING), JPARAM(HADOOP_FS)),
+ jURI, jConfiguration, jUserString);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jFS = jVal.l;
+ }
+ }
+ jRet = (*env)->NewGlobalRef(env, jFS);
+ if (!jRet) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ ret = 0;
+
+done:
+ // Release unnecessary local references
+ destroyLocalReference(env, jConfiguration);
+ destroyLocalReference(env, jFS);
+ destroyLocalReference(env, jURI);
+ destroyLocalReference(env, jCachePath);
+ destroyLocalReference(env, jURIString);
+ destroyLocalReference(env, jUserString);
+ free(cURI);
+ hdfsFreeBuilder(bld);
+
+ if (ret) {
+ errno = ret;
+ return NULL;
+ }
+ return (hdfsFS)jRet;
+}
+
+int hdfsDisconnect(hdfsFS fs)
+{
+ // JAVA EQUIVALENT:
+ // fs.close()
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ int ret;
+ jobject jFS;
+ jthrowable jthr;
+
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Parameters
+ jFS = (jobject)fs;
+
+ //Sanity check
+ if (fs == NULL) {
+ errno = EBADF;
+ return -1;
+ }
+
+ jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
+ "close", "()V");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsDisconnect: FileSystem#close");
+ } else {
+ ret = 0;
+ }
+ (*env)->DeleteGlobalRef(env, jFS);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+/**
+ * Get the default block size of a FileSystem object.
+ *
+ * @param env The Java env
+ * @param jFS The FileSystem object
+ * @param jPath The path to find the default blocksize at
+ * @param out (out param) the default block size
+ *
+ * @return NULL on success; or the exception
+ */
+static jthrowable getDefaultBlockSize(JNIEnv *env, jobject jFS,
+ jobject jPath, jlong *out)
+{
+ jthrowable jthr;
+ jvalue jVal;
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "getDefaultBlockSize", JMETHOD1(JPARAM(HADOOP_PATH), "J"), jPath);
+ if (jthr)
+ return jthr;
+ *out = jVal.j;
+ return NULL;
+}
+
+hdfsFile hdfsOpenFile(hdfsFS fs, const char *path, int flags,
+ int bufferSize, short replication, tSize blockSize)
+{
+ /*
+ JAVA EQUIVALENT:
+ File f = new File(path);
+ FSData{Input|Output}Stream f{is|os} = fs.create(f);
+ return f{is|os};
+ */
+ int accmode = flags & O_ACCMODE;
+ jstring jStrBufferSize = NULL, jStrReplication = NULL;
+ jobject jConfiguration = NULL, jPath = NULL, jFile = NULL;
+ jobject jFS = (jobject)fs;
+ jthrowable jthr;
+ jvalue jVal;
+ hdfsFile file = NULL;
+ int ret;
+ jint jBufferSize = bufferSize;
+ jshort jReplication = replication;
+
+ /* The hadoop java api/signature */
+ const char *method = NULL;
+ const char *signature = NULL;
+
+ /* Get the JNIEnv* corresponding to current thread */
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return NULL;
+ }
+
+
+ if (accmode == O_RDONLY || accmode == O_WRONLY) {
+ /* yay */
+ } else if (accmode == O_RDWR) {
+ fprintf(stderr, "ERROR: cannot open an hdfs file in O_RDWR mode\n");
+ errno = ENOTSUP;
+ return NULL;
+ } else {
+ fprintf(stderr, "ERROR: cannot open an hdfs file in mode 0x%x\n", accmode);
+ errno = EINVAL;
+ return NULL;
+ }
+
+ if ((flags & O_CREAT) && (flags & O_EXCL)) {
+ fprintf(stderr, "WARN: hdfs does not truly support O_CREATE && O_EXCL\n");
+ }
+
+ if (accmode == O_RDONLY) {
+ method = "open";
+ signature = JMETHOD2(JPARAM(HADOOP_PATH), "I", JPARAM(HADOOP_ISTRM));
+ } else if (flags & O_APPEND) {
+ method = "append";
+ signature = JMETHOD1(JPARAM(HADOOP_PATH), JPARAM(HADOOP_OSTRM));
+ } else {
+ method = "create";
+ signature = JMETHOD2(JPARAM(HADOOP_PATH), "ZISJ", JPARAM(HADOOP_OSTRM));
+ }
+
+ /* Create an object of org.apache.hadoop.fs.Path */
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsOpenFile(%s): constructNewObjectOfPath", path);
+ goto done;
+ }
+
+ /* Get the Configuration object from the FileSystem object */
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "getConf", JMETHOD1("", JPARAM(HADOOP_CONF)));
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsOpenFile(%s): FileSystem#getConf", path);
+ goto done;
+ }
+ jConfiguration = jVal.l;
+
+ jStrBufferSize = (*env)->NewStringUTF(env, "io.file.buffer.size");
+ if (!jStrBufferSize) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL, "OOM");
+ goto done;
+ }
+ jStrReplication = (*env)->NewStringUTF(env, "dfs.replication");
+ if (!jStrReplication) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL, "OOM");
+ goto done;
+ }
+
+ if (!bufferSize) {
+ jthr = invokeMethod(env, &jVal, INSTANCE, jConfiguration,
+ HADOOP_CONF, "getInt", "(Ljava/lang/String;I)I",
+ jStrBufferSize, 4096);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, NOPRINT_EXC_FILE_NOT_FOUND |
+ NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_UNRESOLVED_LINK,
+ "hdfsOpenFile(%s): Configuration#getInt(io.file.buffer.size)",
+ path);
+ goto done;
+ }
+ jBufferSize = jVal.i;
+ }
+
+ if ((accmode == O_WRONLY) && (flags & O_APPEND) == 0) {
+ if (!replication) {
+ jthr = invokeMethod(env, &jVal, INSTANCE, jConfiguration,
+ HADOOP_CONF, "getInt", "(Ljava/lang/String;I)I",
+ jStrReplication, 1);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsOpenFile(%s): Configuration#getInt(dfs.replication)",
+ path);
+ goto done;
+ }
+ jReplication = (jshort)jVal.i;
+ }
+ }
+
+ /* Create and return either the FSDataInputStream or
+ FSDataOutputStream references jobject jStream */
+
+ // READ?
+ if (accmode == O_RDONLY) {
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ method, signature, jPath, jBufferSize);
+ } else if ((accmode == O_WRONLY) && (flags & O_APPEND)) {
+ // WRITE/APPEND?
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ method, signature, jPath);
+ } else {
+ // WRITE/CREATE
+ jboolean jOverWrite = 1;
+ jlong jBlockSize = blockSize;
+
+ if (jBlockSize == 0) {
+ jthr = getDefaultBlockSize(env, jFS, jPath, &jBlockSize);
+ if (jthr) {
+ ret = EIO;
+ goto done;
+ }
+ }
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ method, signature, jPath, jOverWrite,
+ jBufferSize, jReplication, jBlockSize);
+ }
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsOpenFile(%s): FileSystem#%s(%s)", path, method, signature);
+ goto done;
+ }
+ jFile = jVal.l;
+
+ file = calloc(1, sizeof(struct hdfsFile_internal));
+ if (!file) {
+ fprintf(stderr, "hdfsOpenFile(%s): OOM create hdfsFile\n", path);
+ ret = ENOMEM;
+ goto done;
+ }
+ file->file = (*env)->NewGlobalRef(env, jFile);
+ if (!file->file) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsOpenFile(%s): NewGlobalRef", path);
+ goto done;
+ }
+ file->type = (((flags & O_WRONLY) == 0) ? HDFS_STREAM_INPUT :
+ HDFS_STREAM_OUTPUT);
+ file->flags = 0;
+
+ if ((flags & O_WRONLY) == 0) {
+ // Try a test read to see if we can do direct reads
+ char buf;
+ if (readDirect(fs, file, &buf, 0) == 0) {
+ // Success - 0-byte read should return 0
+ file->flags |= HDFS_FILE_SUPPORTS_DIRECT_READ;
+ } else if (errno != ENOTSUP) {
+ // Unexpected error. Clear it, don't set the direct flag.
+ fprintf(stderr,
+ "hdfsOpenFile(%s): WARN: Unexpected error %d when testing "
+ "for direct read compatibility\n", path, errno);
+ }
+ }
+ ret = 0;
+
+done:
+ destroyLocalReference(env, jStrBufferSize);
+ destroyLocalReference(env, jStrReplication);
+ destroyLocalReference(env, jConfiguration);
+ destroyLocalReference(env, jPath);
+ destroyLocalReference(env, jFile);
+ if (ret) {
+ if (file) {
+ if (file->file) {
+ (*env)->DeleteGlobalRef(env, file->file);
+ }
+ free(file);
+ }
+ errno = ret;
+ return NULL;
+ }
+ return file;
+}
+
+int hdfsTruncateFile(hdfsFS fs, const char* path, tOffset newlength)
+{
+ jobject jFS = (jobject)fs;
+ jthrowable jthr;
+ jvalue jVal;
+ jobject jPath = NULL;
+
+ JNIEnv *env = getJNIEnv();
+
+ if (!env) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ /* Create an object of org.apache.hadoop.fs.Path */
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsTruncateFile(%s): constructNewObjectOfPath", path);
+ return -1;
+ }
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "truncate", JMETHOD2(JPARAM(HADOOP_PATH), "J", "Z"),
+ jPath, newlength);
+ destroyLocalReference(env, jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsTruncateFile(%s): FileSystem#truncate", path);
+ return -1;
+ }
+ if (jVal.z == JNI_TRUE) {
+ return 1;
+ }
+ return 0;
+}
+
+int hdfsUnbufferFile(hdfsFile file)
+{
+ int ret;
+ jthrowable jthr;
+ JNIEnv *env = getJNIEnv();
+
+ if (!env) {
+ ret = EINTERNAL;
+ goto done;
+ }
+ if (file->type != HDFS_STREAM_INPUT) {
+ ret = ENOTSUP;
+ goto done;
+ }
+ jthr = invokeMethod(env, NULL, INSTANCE, file->file, HADOOP_ISTRM,
+ "unbuffer", "()V");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ HADOOP_ISTRM "#unbuffer failed:");
+ goto done;
+ }
+ ret = 0;
+
+done:
+ errno = ret;
+ return ret;
+}
+
+int hdfsCloseFile(hdfsFS fs, hdfsFile file)
+{
+ int ret;
+ // JAVA EQUIVALENT:
+ // file.close
+
+ //The interface whose 'close' method to be called
+ const char *interface;
+ const char *interfaceShortName;
+
+ //Caught exception
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Sanity check
+ if (!file || file->type == HDFS_STREAM_UNINITIALIZED) {
+ errno = EBADF;
+ return -1;
+ }
+
+ interface = (file->type == HDFS_STREAM_INPUT) ?
+ HADOOP_ISTRM : HADOOP_OSTRM;
+
+ jthr = invokeMethod(env, NULL, INSTANCE, file->file, interface,
+ "close", "()V");
+ if (jthr) {
+ interfaceShortName = (file->type == HDFS_STREAM_INPUT) ?
+ "FSDataInputStream" : "FSDataOutputStream";
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "%s#close", interfaceShortName);
+ } else {
+ ret = 0;
+ }
+
+ //De-allocate memory
+ (*env)->DeleteGlobalRef(env, file->file);
+ free(file);
+
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsExists(hdfsFS fs, const char *path)
+{
+ JNIEnv *env = getJNIEnv();
+ jobject jPath;
+ jvalue jVal;
+ jobject jFS = (jobject)fs;
+ jthrowable jthr;
+
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ if (path == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsExists: constructNewObjectOfPath");
+ return -1;
+ }
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "exists", JMETHOD1(JPARAM(HADOOP_PATH), "Z"), jPath);
+ destroyLocalReference(env, jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsExists: invokeMethod(%s)",
+ JMETHOD1(JPARAM(HADOOP_PATH), "Z"));
+ return -1;
+ }
+ if (jVal.z) {
+ return 0;
+ } else {
+ errno = ENOENT;
+ return -1;
+ }
+}
+
+// Checks input file for readiness for reading.
+static int readPrepare(JNIEnv* env, hdfsFS fs, hdfsFile f,
+ jobject* jInputStream)
+{
+ *jInputStream = (jobject)(f ? f->file : NULL);
+
+ //Sanity check
+ if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
+ errno = EBADF;
+ return -1;
+ }
+
+ //Error checking... make sure that this file is 'readable'
+ if (f->type != HDFS_STREAM_INPUT) {
+ fprintf(stderr, "Cannot read from a non-InputStream object!\n");
+ errno = EINVAL;
+ return -1;
+ }
+
+ return 0;
+}
+
+tSize hdfsRead(hdfsFS fs, hdfsFile f, void* buffer, tSize length)
+{
+ jobject jInputStream;
+ jbyteArray jbRarray;
+ jint noReadBytes = length;
+ jvalue jVal;
+ jthrowable jthr;
+ JNIEnv* env;
+
+ if (length == 0) {
+ return 0;
+ } else if (length < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ if (f->flags & HDFS_FILE_SUPPORTS_DIRECT_READ) {
+ return readDirect(fs, f, buffer, length);
+ }
+
+ // JAVA EQUIVALENT:
+ // byte [] bR = new byte[length];
+ // fis.read(bR);
+
+ //Get the JNIEnv* corresponding to current thread
+ env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Parameters
+ if (readPrepare(env, fs, f, &jInputStream) == -1) {
+ return -1;
+ }
+
+ //Read the requisite bytes
+ jbRarray = (*env)->NewByteArray(env, length);
+ if (!jbRarray) {
+ errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsRead: NewByteArray");
+ return -1;
+ }
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jInputStream, HADOOP_ISTRM,
+ "read", "([B)I", jbRarray);
+ if (jthr) {
+ destroyLocalReference(env, jbRarray);
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsRead: FSDataInputStream#read");
+ return -1;
+ }
+ if (jVal.i < 0) {
+ // EOF
+ destroyLocalReference(env, jbRarray);
+ return 0;
+ } else if (jVal.i == 0) {
+ destroyLocalReference(env, jbRarray);
+ errno = EINTR;
+ return -1;
+ }
+ (*env)->GetByteArrayRegion(env, jbRarray, 0, noReadBytes, buffer);
+ destroyLocalReference(env, jbRarray);
+ if ((*env)->ExceptionCheck(env)) {
+ errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsRead: GetByteArrayRegion");
+ return -1;
+ }
+ return jVal.i;
+}
+
+// Reads using the read(ByteBuffer) API, which does fewer copies
+tSize readDirect(hdfsFS fs, hdfsFile f, void* buffer, tSize length)
+{
+ // JAVA EQUIVALENT:
+ // ByteBuffer bbuffer = ByteBuffer.allocateDirect(length) // wraps C buffer
+ // fis.read(bbuffer);
+
+ jobject jInputStream;
+ jvalue jVal;
+ jthrowable jthr;
+ jobject bb;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ if (readPrepare(env, fs, f, &jInputStream) == -1) {
+ return -1;
+ }
+
+ //Read the requisite bytes
+ bb = (*env)->NewDirectByteBuffer(env, buffer, length);
+ if (bb == NULL) {
+ errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "readDirect: NewDirectByteBuffer");
+ return -1;
+ }
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jInputStream,
+ HADOOP_ISTRM, "read", "(Ljava/nio/ByteBuffer;)I", bb);
+ destroyLocalReference(env, bb);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "readDirect: FSDataInputStream#read");
+ return -1;
+ }
+ return (jVal.i < 0) ? 0 : jVal.i;
+}
+
+tSize hdfsPread(hdfsFS fs, hdfsFile f, tOffset position,
+ void* buffer, tSize length)
+{
+ JNIEnv* env;
+ jbyteArray jbRarray;
+ jvalue jVal;
+ jthrowable jthr;
+
+ if (length == 0) {
+ return 0;
+ } else if (length < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
+ errno = EBADF;
+ return -1;
+ }
+
+ env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Error checking... make sure that this file is 'readable'
+ if (f->type != HDFS_STREAM_INPUT) {
+ fprintf(stderr, "Cannot read from a non-InputStream object!\n");
+ errno = EINVAL;
+ return -1;
+ }
+
+ // JAVA EQUIVALENT:
+ // byte [] bR = new byte[length];
+ // fis.read(pos, bR, 0, length);
+ jbRarray = (*env)->NewByteArray(env, length);
+ if (!jbRarray) {
+ errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsPread: NewByteArray");
+ return -1;
+ }
+ jthr = invokeMethod(env, &jVal, INSTANCE, f->file, HADOOP_ISTRM,
+ "read", "(J[BII)I", position, jbRarray, 0, length);
+ if (jthr) {
+ destroyLocalReference(env, jbRarray);
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsPread: FSDataInputStream#read");
+ return -1;
+ }
+ if (jVal.i < 0) {
+ // EOF
+ destroyLocalReference(env, jbRarray);
+ return 0;
+ } else if (jVal.i == 0) {
+ destroyLocalReference(env, jbRarray);
+ errno = EINTR;
+ return -1;
+ }
+ (*env)->GetByteArrayRegion(env, jbRarray, 0, jVal.i, buffer);
+ destroyLocalReference(env, jbRarray);
+ if ((*env)->ExceptionCheck(env)) {
+ errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsPread: GetByteArrayRegion");
+ return -1;
+ }
+ return jVal.i;
+}
+
+tSize hdfsWrite(hdfsFS fs, hdfsFile f, const void* buffer, tSize length)
+{
+ // JAVA EQUIVALENT
+ // byte b[] = str.getBytes();
+ // fso.write(b);
+
+ jobject jOutputStream;
+ jbyteArray jbWarray;
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Sanity check
+ if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
+ errno = EBADF;
+ return -1;
+ }
+
+ jOutputStream = f->file;
+
+ if (length < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ //Error checking... make sure that this file is 'writable'
+ if (f->type != HDFS_STREAM_OUTPUT) {
+ fprintf(stderr, "Cannot write into a non-OutputStream object!\n");
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (length < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ if (length == 0) {
+ return 0;
+ }
+ //Write the requisite bytes into the file
+ jbWarray = (*env)->NewByteArray(env, length);
+ if (!jbWarray) {
+ errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsWrite: NewByteArray");
+ return -1;
+ }
+ (*env)->SetByteArrayRegion(env, jbWarray, 0, length, buffer);
+ if ((*env)->ExceptionCheck(env)) {
+ destroyLocalReference(env, jbWarray);
+ errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsWrite(length = %d): SetByteArrayRegion", length);
+ return -1;
+ }
+ jthr = invokeMethod(env, NULL, INSTANCE, jOutputStream,
+ HADOOP_OSTRM, "write", "([B)V", jbWarray);
+ destroyLocalReference(env, jbWarray);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsWrite: FSDataOutputStream#write");
+ return -1;
+ }
+ // Unlike most Java streams, FSDataOutputStream never does partial writes.
+ // If we succeeded, all the data was written.
+ return length;
+}
+
+int hdfsSeek(hdfsFS fs, hdfsFile f, tOffset desiredPos)
+{
+ // JAVA EQUIVALENT
+ // fis.seek(pos);
+
+ jobject jInputStream;
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Sanity check
+ if (!f || f->type != HDFS_STREAM_INPUT) {
+ errno = EBADF;
+ return -1;
+ }
+
+ jInputStream = f->file;
+ jthr = invokeMethod(env, NULL, INSTANCE, jInputStream,
+ HADOOP_ISTRM, "seek", "(J)V", desiredPos);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsSeek(desiredPos=%" PRId64 ")"
+ ": FSDataInputStream#seek", desiredPos);
+ return -1;
+ }
+ return 0;
+}
+
+
+
+tOffset hdfsTell(hdfsFS fs, hdfsFile f)
+{
+ // JAVA EQUIVALENT
+ // pos = f.getPos();
+
+ jobject jStream;
+ const char *interface;
+ jvalue jVal;
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Sanity check
+ if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
+ errno = EBADF;
+ return -1;
+ }
+
+ //Parameters
+ jStream = f->file;
+ interface = (f->type == HDFS_STREAM_INPUT) ?
+ HADOOP_ISTRM : HADOOP_OSTRM;
+ jthr = invokeMethod(env, &jVal, INSTANCE, jStream,
+ interface, "getPos", "()J");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsTell: %s#getPos",
+ ((f->type == HDFS_STREAM_INPUT) ? "FSDataInputStream" :
+ "FSDataOutputStream"));
+ return -1;
+ }
+ return jVal.j;
+}
+
+int hdfsFlush(hdfsFS fs, hdfsFile f)
+{
+ // JAVA EQUIVALENT
+ // fos.flush();
+
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Sanity check
+ if (!f || f->type != HDFS_STREAM_OUTPUT) {
+ errno = EBADF;
+ return -1;
+ }
+ jthr = invokeMethod(env, NULL, INSTANCE, f->file,
+ HADOOP_OSTRM, "flush", "()V");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsFlush: FSDataInputStream#flush");
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsHFlush(hdfsFS fs, hdfsFile f)
+{
+ jobject jOutputStream;
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Sanity check
+ if (!f || f->type != HDFS_STREAM_OUTPUT) {
+ errno = EBADF;
+ return -1;
+ }
+
+ jOutputStream = f->file;
+ jthr = invokeMethod(env, NULL, INSTANCE, jOutputStream,
+ HADOOP_OSTRM, "hflush", "()V");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsHFlush: FSDataOutputStream#hflush");
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsHSync(hdfsFS fs, hdfsFile f)
+{
+ jobject jOutputStream;
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Sanity check
+ if (!f || f->type != HDFS_STREAM_OUTPUT) {
+ errno = EBADF;
+ return -1;
+ }
+
+ jOutputStream = f->file;
+ jthr = invokeMethod(env, NULL, INSTANCE, jOutputStream,
+ HADOOP_OSTRM, "hsync", "()V");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsHSync: FSDataOutputStream#hsync");
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsAvailable(hdfsFS fs, hdfsFile f)
+{
+ // JAVA EQUIVALENT
+ // fis.available();
+
+ jobject jInputStream;
+ jvalue jVal;
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Sanity check
+ if (!f || f->type != HDFS_STREAM_INPUT) {
+ errno = EBADF;
+ return -1;
+ }
+
+ //Parameters
+ jInputStream = f->file;
+ jthr = invokeMethod(env, &jVal, INSTANCE, jInputStream,
+ HADOOP_ISTRM, "available", "()I");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsAvailable: FSDataInputStream#available");
+ return -1;
+ }
+ return jVal.i;
+}
+
+static int hdfsCopyImpl(hdfsFS srcFS, const char *src, hdfsFS dstFS,
+ const char *dst, jboolean deleteSource)
+{
+ //JAVA EQUIVALENT
+ // FileUtil#copy(srcFS, srcPath, dstFS, dstPath,
+ // deleteSource = false, conf)
+
+ //Parameters
+ jobject jSrcFS = (jobject)srcFS;
+ jobject jDstFS = (jobject)dstFS;
+ jobject jConfiguration = NULL, jSrcPath = NULL, jDstPath = NULL;
+ jthrowable jthr;
+ jvalue jVal;
+ int ret;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ jthr = constructNewObjectOfPath(env, src, &jSrcPath);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsCopyImpl(src=%s): constructNewObjectOfPath", src);
+ goto done;
+ }
+ jthr = constructNewObjectOfPath(env, dst, &jDstPath);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsCopyImpl(dst=%s): constructNewObjectOfPath", dst);
+ goto done;
+ }
+
+ //Create the org.apache.hadoop.conf.Configuration object
+ jthr = constructNewObjectOfClass(env, &jConfiguration,
+ HADOOP_CONF, "()V");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsCopyImpl: Configuration constructor");
+ goto done;
+ }
+
+ //FileUtil#copy
+ jthr = invokeMethod(env, &jVal, STATIC,
+ NULL, "org/apache/hadoop/fs/FileUtil", "copy",
+ "(Lorg/apache/hadoop/fs/FileSystem;Lorg/apache/hadoop/fs/Path;"
+ "Lorg/apache/hadoop/fs/FileSystem;Lorg/apache/hadoop/fs/Path;"
+ "ZLorg/apache/hadoop/conf/Configuration;)Z",
+ jSrcFS, jSrcPath, jDstFS, jDstPath, deleteSource,
+ jConfiguration);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsCopyImpl(src=%s, dst=%s, deleteSource=%d): "
+ "FileUtil#copy", src, dst, deleteSource);
+ goto done;
+ }
+ if (!jVal.z) {
+ ret = EIO;
+ goto done;
+ }
+ ret = 0;
+
+done:
+ destroyLocalReference(env, jConfiguration);
+ destroyLocalReference(env, jSrcPath);
+ destroyLocalReference(env, jDstPath);
+
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsCopy(hdfsFS srcFS, const char *src, hdfsFS dstFS, const char *dst)
+{
+ return hdfsCopyImpl(srcFS, src, dstFS, dst, 0);
+}
+
+int hdfsMove(hdfsFS srcFS, const char *src, hdfsFS dstFS, const char *dst)
+{
+ return hdfsCopyImpl(srcFS, src, dstFS, dst, 1);
+}
+
+int hdfsDelete(hdfsFS fs, const char *path, int recursive)
+{
+ // JAVA EQUIVALENT:
+ // Path p = new Path(path);
+ // bool retval = fs.delete(p, recursive);
+
+ jobject jFS = (jobject)fs;
+ jthrowable jthr;
+ jobject jPath;
+ jvalue jVal;
+ jboolean jRecursive;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsDelete(path=%s): constructNewObjectOfPath", path);
+ return -1;
+ }
+ jRecursive = recursive ? JNI_TRUE : JNI_FALSE;
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "delete", "(Lorg/apache/hadoop/fs/Path;Z)Z",
+ jPath, jRecursive);
+ destroyLocalReference(env, jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsDelete(path=%s, recursive=%d): "
+ "FileSystem#delete", path, recursive);
+ return -1;
+ }
+ if (!jVal.z) {
+ errno = EIO;
+ return -1;
+ }
+ return 0;
+}
+
+
+
+int hdfsRename(hdfsFS fs, const char *oldPath, const char *newPath)
+{
+ // JAVA EQUIVALENT:
+ // Path old = new Path(oldPath);
+ // Path new = new Path(newPath);
+ // fs.rename(old, new);
+
+ jobject jFS = (jobject)fs;
+ jthrowable jthr;
+ jobject jOldPath = NULL, jNewPath = NULL;
+ int ret = -1;
+ jvalue jVal;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ jthr = constructNewObjectOfPath(env, oldPath, &jOldPath );
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsRename: constructNewObjectOfPath(%s)", oldPath);
+ goto done;
+ }
+ jthr = constructNewObjectOfPath(env, newPath, &jNewPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsRename: constructNewObjectOfPath(%s)", newPath);
+ goto done;
+ }
+
+ // Rename the file
+ // TODO: use rename2 here? (See HDFS-3592)
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS, "rename",
+ JMETHOD2(JPARAM(HADOOP_PATH), JPARAM(HADOOP_PATH), "Z"),
+ jOldPath, jNewPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsRename(oldPath=%s, newPath=%s): FileSystem#rename",
+ oldPath, newPath);
+ goto done;
+ }
+ if (!jVal.z) {
+ errno = EIO;
+ goto done;
+ }
+ ret = 0;
+
+done:
+ destroyLocalReference(env, jOldPath);
+ destroyLocalReference(env, jNewPath);
+ return ret;
+}
+
+
+
+char* hdfsGetWorkingDirectory(hdfsFS fs, char* buffer, size_t bufferSize)
+{
+ // JAVA EQUIVALENT:
+ // Path p = fs.getWorkingDirectory();
+ // return p.toString()
+
+ jobject jPath = NULL;
+ jstring jPathString = NULL;
+ jobject jFS = (jobject)fs;
+ jvalue jVal;
+ jthrowable jthr;
+ int ret;
+ const char *jPathChars = NULL;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return NULL;
+ }
+
+ //FileSystem#getWorkingDirectory()
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS,
+ HADOOP_FS, "getWorkingDirectory",
+ "()Lorg/apache/hadoop/fs/Path;");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetWorkingDirectory: FileSystem#getWorkingDirectory");
+ goto done;
+ }
+ jPath = jVal.l;
+ if (!jPath) {
+ fprintf(stderr, "hdfsGetWorkingDirectory: "
+ "FileSystem#getWorkingDirectory returned NULL");
+ ret = -EIO;
+ goto done;
+ }
+
+ //Path#toString()
+ jthr = invokeMethod(env, &jVal, INSTANCE, jPath,
+ "org/apache/hadoop/fs/Path", "toString",
+ "()Ljava/lang/String;");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetWorkingDirectory: Path#toString");
+ goto done;
+ }
+ jPathString = jVal.l;
+ jPathChars = (*env)->GetStringUTFChars(env, jPathString, NULL);
+ if (!jPathChars) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsGetWorkingDirectory: GetStringUTFChars");
+ goto done;
+ }
+
+ //Copy to user-provided buffer
+ ret = snprintf(buffer, bufferSize, "%s", jPathChars);
+ if (ret >= bufferSize) {
+ ret = ENAMETOOLONG;
+ goto done;
+ }
+ ret = 0;
+
+done:
+ if (jPathChars) {
+ (*env)->ReleaseStringUTFChars(env, jPathString, jPathChars);
+ }
+ destroyLocalReference(env, jPath);
+ destroyLocalReference(env, jPathString);
+
+ if (ret) {
+ errno = ret;
+ return NULL;
+ }
+ return buffer;
+}
+
+
+
+int hdfsSetWorkingDirectory(hdfsFS fs, const char *path)
+{
+ // JAVA EQUIVALENT:
+ // fs.setWorkingDirectory(Path(path));
+
+ jobject jFS = (jobject)fs;
+ jthrowable jthr;
+ jobject jPath;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Create an object of org.apache.hadoop.fs.Path
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsSetWorkingDirectory(%s): constructNewObjectOfPath",
+ path);
+ return -1;
+ }
+
+ //FileSystem#setWorkingDirectory()
+ jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
+ "setWorkingDirectory",
+ "(Lorg/apache/hadoop/fs/Path;)V", jPath);
+ destroyLocalReference(env, jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, NOPRINT_EXC_ILLEGAL_ARGUMENT,
+ "hdfsSetWorkingDirectory(%s): FileSystem#setWorkingDirectory",
+ path);
+ return -1;
+ }
+ return 0;
+}
+
+
+
+int hdfsCreateDirectory(hdfsFS fs, const char *path)
+{
+ // JAVA EQUIVALENT:
+ // fs.mkdirs(new Path(path));
+
+ jobject jFS = (jobject)fs;
+ jobject jPath;
+ jthrowable jthr;
+ jvalue jVal;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Create an object of org.apache.hadoop.fs.Path
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsCreateDirectory(%s): constructNewObjectOfPath", path);
+ return -1;
+ }
+
+ //Create the directory
+ jVal.z = 0;
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "mkdirs", "(Lorg/apache/hadoop/fs/Path;)Z",
+ jPath);
+ destroyLocalReference(env, jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr,
+ NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_FILE_NOT_FOUND |
+ NOPRINT_EXC_UNRESOLVED_LINK | NOPRINT_EXC_PARENT_NOT_DIRECTORY,
+ "hdfsCreateDirectory(%s): FileSystem#mkdirs", path);
+ return -1;
+ }
+ if (!jVal.z) {
+ // It's unclear under exactly which conditions FileSystem#mkdirs
+ // is supposed to return false (as opposed to throwing an exception.)
+ // It seems like the current code never actually returns false.
+ // So we're going to translate this to EIO, since there seems to be
+ // nothing more specific we can do with it.
+ errno = EIO;
+ return -1;
+ }
+ return 0;
+}
+
+
+int hdfsSetReplication(hdfsFS fs, const char *path, int16_t replication)
+{
+ // JAVA EQUIVALENT:
+ // fs.setReplication(new Path(path), replication);
+
+ jobject jFS = (jobject)fs;
+ jthrowable jthr;
+ jobject jPath;
+ jvalue jVal;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Create an object of org.apache.hadoop.fs.Path
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsSetReplication(path=%s): constructNewObjectOfPath", path);
+ return -1;
+ }
+
+ //Create the directory
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "setReplication", "(Lorg/apache/hadoop/fs/Path;S)Z",
+ jPath, replication);
+ destroyLocalReference(env, jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsSetReplication(path=%s, replication=%d): "
+ "FileSystem#setReplication", path, replication);
+ return -1;
+ }
+ if (!jVal.z) {
+ // setReplication returns false "if file does not exist or is a
+ // directory." So the nearest translation to that is ENOENT.
+ errno = ENOENT;
+ return -1;
+ }
+
+ return 0;
+}
+
+int hdfsChown(hdfsFS fs, const char *path, const char *owner, const char *group)
+{
+ // JAVA EQUIVALENT:
+ // fs.setOwner(path, owner, group)
+
+ jobject jFS = (jobject)fs;
+ jobject jPath = NULL;
+ jstring jOwner = NULL, jGroup = NULL;
+ jthrowable jthr;
+ int ret;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ if (owner == NULL && group == NULL) {
+ return 0;
+ }
+
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsChown(path=%s): constructNewObjectOfPath", path);
+ goto done;
+ }
+
+ jthr = newJavaStr(env, owner, &jOwner);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsChown(path=%s): newJavaStr(%s)", path, owner);
+ goto done;
+ }
+ jthr = newJavaStr(env, group, &jGroup);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsChown(path=%s): newJavaStr(%s)", path, group);
+ goto done;
+ }
+
+ //Create the directory
+ jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
+ "setOwner", JMETHOD3(JPARAM(HADOOP_PATH),
+ JPARAM(JAVA_STRING), JPARAM(JAVA_STRING), JAVA_VOID),
+ jPath, jOwner, jGroup);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr,
+ NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_FILE_NOT_FOUND |
+ NOPRINT_EXC_UNRESOLVED_LINK,
+ "hdfsChown(path=%s, owner=%s, group=%s): "
+ "FileSystem#setOwner", path, owner, group);
+ goto done;
+ }
+ ret = 0;
+
+done:
+ destroyLocalReference(env, jPath);
+ destroyLocalReference(env, jOwner);
+ destroyLocalReference(env, jGroup);
+
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsChmod(hdfsFS fs, const char *path, short mode)
+{
+ int ret;
+ // JAVA EQUIVALENT:
+ // fs.setPermission(path, FsPermission)
+
+ jthrowable jthr;
+ jobject jPath = NULL, jPermObj = NULL;
+ jobject jFS = (jobject)fs;
+ jshort jmode = mode;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ // construct jPerm = FsPermission.createImmutable(short mode);
+ jthr = constructNewObjectOfClass(env, &jPermObj,
+ HADOOP_FSPERM,"(S)V",jmode);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "constructNewObjectOfClass(%s)", HADOOP_FSPERM);
+ return -1;
+ }
+
+ //Create an object of org.apache.hadoop.fs.Path
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsChmod(%s): constructNewObjectOfPath", path);
+ goto done;
+ }
+
+ //Create the directory
+ jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
+ "setPermission",
+ JMETHOD2(JPARAM(HADOOP_PATH), JPARAM(HADOOP_FSPERM), JAVA_VOID),
+ jPath, jPermObj);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr,
+ NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_FILE_NOT_FOUND |
+ NOPRINT_EXC_UNRESOLVED_LINK,
+ "hdfsChmod(%s): FileSystem#setPermission", path);
+ goto done;
+ }
+ ret = 0;
+
+done:
+ destroyLocalReference(env, jPath);
+ destroyLocalReference(env, jPermObj);
+
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsUtime(hdfsFS fs, const char *path, tTime mtime, tTime atime)
+{
+ // JAVA EQUIVALENT:
+ // fs.setTimes(src, mtime, atime)
+
+ jthrowable jthr;
+ jobject jFS = (jobject)fs;
+ jobject jPath;
+ static const tTime NO_CHANGE = -1;
+ jlong jmtime, jatime;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //Create an object of org.apache.hadoop.fs.Path
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsUtime(path=%s): constructNewObjectOfPath", path);
+ return -1;
+ }
+
+ jmtime = (mtime == NO_CHANGE) ? -1 : (mtime * (jlong)1000);
+ jatime = (atime == NO_CHANGE) ? -1 : (atime * (jlong)1000);
+
+ jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
+ "setTimes", JMETHOD3(JPARAM(HADOOP_PATH), "J", "J", JAVA_VOID),
+ jPath, jmtime, jatime);
+ destroyLocalReference(env, jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr,
+ NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_FILE_NOT_FOUND |
+ NOPRINT_EXC_UNRESOLVED_LINK,
+ "hdfsUtime(path=%s): FileSystem#setTimes", path);
+ return -1;
+ }
+ return 0;
+}
+
+/**
+ * Zero-copy options.
+ *
+ * We cache the EnumSet of ReadOptions which has to be passed into every
+ * readZero call, to avoid reconstructing it each time. This cache is cleared
+ * whenever an element changes.
+ */
+struct hadoopRzOptions
+{
+ JNIEnv *env;
+ int skipChecksums;
+ jobject byteBufferPool;
+ jobject cachedEnumSet;
+};
+
+struct hadoopRzOptions *hadoopRzOptionsAlloc(void)
+{
+ struct hadoopRzOptions *opts;
+ JNIEnv *env;
+
+ env = getJNIEnv();
+ if (!env) {
+ // Check to make sure the JNI environment is set up properly.
+ errno = EINTERNAL;
+ return NULL;
+ }
+ opts = calloc(1, sizeof(struct hadoopRzOptions));
+ if (!opts) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ return opts;
+}
+
+static void hadoopRzOptionsClearCached(JNIEnv *env,
+ struct hadoopRzOptions *opts)
+{
+ if (!opts->cachedEnumSet) {
+ return;
+ }
+ (*env)->DeleteGlobalRef(env, opts->cachedEnumSet);
+ opts->cachedEnumSet = NULL;
+}
+
+int hadoopRzOptionsSetSkipChecksum(
+ struct hadoopRzOptions *opts, int skip)
+{
+ JNIEnv *env;
+ env = getJNIEnv();
+ if (!env) {
+ errno = EINTERNAL;
+ return -1;
+ }
+ hadoopRzOptionsClearCached(env, opts);
+ opts->skipChecksums = !!skip;
+ return 0;
+}
+
+int hadoopRzOptionsSetByteBufferPool(
+ struct hadoopRzOptions *opts, const char *className)
+{
+ JNIEnv *env;
+ jthrowable jthr;
+ jobject byteBufferPool = NULL;
+
+ env = getJNIEnv();
+ if (!env) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ if (className) {
+ // Note: we don't have to call hadoopRzOptionsClearCached in this
+ // function, since the ByteBufferPool is passed separately from the
+ // EnumSet of ReadOptions.
+
+ jthr = constructNewObjectOfClass(env, &byteBufferPool, className, "()V");
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hadoopRzOptionsSetByteBufferPool(className=%s): ", className);
+ errno = EINVAL;
+ return -1;
+ }
+ }
+ if (opts->byteBufferPool) {
+ // Delete any previous ByteBufferPool we had.
+ (*env)->DeleteGlobalRef(env, opts->byteBufferPool);
+ }
+ opts->byteBufferPool = byteBufferPool;
+ return 0;
+}
+
+void hadoopRzOptionsFree(struct hadoopRzOptions *opts)
+{
+ JNIEnv *env;
+ env = getJNIEnv();
+ if (!env) {
+ return;
+ }
+ hadoopRzOptionsClearCached(env, opts);
+ if (opts->byteBufferPool) {
+ (*env)->DeleteGlobalRef(env, opts->byteBufferPool);
+ opts->byteBufferPool = NULL;
+ }
+ free(opts);
+}
+
+struct hadoopRzBuffer
+{
+ jobject byteBuffer;
+ uint8_t *ptr;
+ int32_t length;
+ int direct;
+};
+
+static jthrowable hadoopRzOptionsGetEnumSet(JNIEnv *env,
+ struct hadoopRzOptions *opts, jobject *enumSet)
+{
+ jthrowable jthr = NULL;
+ jobject enumInst = NULL, enumSetObj = NULL;
+ jvalue jVal;
+
+ if (opts->cachedEnumSet) {
+ // If we cached the value, return it now.
+ *enumSet = opts->cachedEnumSet;
+ goto done;
+ }
+ if (opts->skipChecksums) {
+ jthr = fetchEnumInstance(env, READ_OPTION,
+ "SKIP_CHECKSUMS", &enumInst);
+ if (jthr) {
+ goto done;
+ }
+ jthr = invokeMethod(env, &jVal, STATIC, NULL,
+ "java/util/EnumSet", "of",
+ "(Ljava/lang/Enum;)Ljava/util/EnumSet;", enumInst);
+ if (jthr) {
+ goto done;
+ }
+ enumSetObj = jVal.l;
+ } else {
+ jclass clazz = (*env)->FindClass(env, READ_OPTION);
+ if (!clazz) {
+ jthr = newRuntimeError(env, "failed "
+ "to find class for %s", READ_OPTION);
+ goto done;
+ }
+ jthr = invokeMethod(env, &jVal, STATIC, NULL,
+ "java/util/EnumSet", "noneOf",
+ "(Ljava/lang/Class;)Ljava/util/EnumSet;", clazz);
+ enumSetObj = jVal.l;
+ }
+ // create global ref
+ opts->cachedEnumSet = (*env)->NewGlobalRef(env, enumSetObj);
+ if (!opts->cachedEnumSet) {
+ jthr = getPendingExceptionAndClear(env);
+ goto done;
+ }
+ *enumSet = opts->cachedEnumSet;
+ jthr = NULL;
+done:
+ (*env)->DeleteLocalRef(env, enumInst);
+ (*env)->DeleteLocalRef(env, enumSetObj);
+ return jthr;
+}
+
+static int hadoopReadZeroExtractBuffer(JNIEnv *env,
+ const struct hadoopRzOptions *opts, struct hadoopRzBuffer *buffer)
+{
+ int ret;
+ jthrowable jthr;
+ jvalue jVal;
+ uint8_t *directStart;
+ void *mallocBuf = NULL;
+ jint position;
+ jarray array = NULL;
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, buffer->byteBuffer,
+ "java/nio/ByteBuffer", "remaining", "()I");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hadoopReadZeroExtractBuffer: ByteBuffer#remaining failed: ");
+ goto done;
+ }
+ buffer->length = jVal.i;
+ jthr = invokeMethod(env, &jVal, INSTANCE, buffer->byteBuffer,
+ "java/nio/ByteBuffer", "position", "()I");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hadoopReadZeroExtractBuffer: ByteBuffer#position failed: ");
+ goto done;
+ }
+ position = jVal.i;
+ directStart = (*env)->GetDirectBufferAddress(env, buffer->byteBuffer);
+ if (directStart) {
+ // Handle direct buffers.
+ buffer->ptr = directStart + position;
+ buffer->direct = 1;
+ ret = 0;
+ goto done;
+ }
+ // Handle indirect buffers.
+ // The JNI docs don't say that GetDirectBufferAddress throws any exceptions
+ // when it fails. However, they also don't clearly say that it doesn't. It
+ // seems safest to clear any pending exceptions here, to prevent problems on
+ // various JVMs.
+ (*env)->ExceptionClear(env);
+ if (!opts->byteBufferPool) {
+ fputs("hadoopReadZeroExtractBuffer: we read through the "
+ "zero-copy path, but failed to get the address of the buffer via "
+ "GetDirectBufferAddress. Please make sure your JVM supports "
+ "GetDirectBufferAddress.\n", stderr);
+ ret = ENOTSUP;
+ goto done;
+ }
+ // Get the backing array object of this buffer.
+ jthr = invokeMethod(env, &jVal, INSTANCE, buffer->byteBuffer,
+ "java/nio/ByteBuffer", "array", "()[B");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hadoopReadZeroExtractBuffer: ByteBuffer#array failed: ");
+ goto done;
+ }
+ array = jVal.l;
+ if (!array) {
+ fputs("hadoopReadZeroExtractBuffer: ByteBuffer#array returned NULL.",
+ stderr);
+ ret = EIO;
+ goto done;
+ }
+ mallocBuf = malloc(buffer->length);
+ if (!mallocBuf) {
+ fprintf(stderr, "hadoopReadZeroExtractBuffer: failed to allocate %d bytes of memory\n",
+ buffer->length);
+ ret = ENOMEM;
+ goto done;
+ }
+ (*env)->GetByteArrayRegion(env, array, position, buffer->length, mallocBuf);
+ jthr = (*env)->ExceptionOccurred(env);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hadoopReadZeroExtractBuffer: GetByteArrayRegion failed: ");
+ goto done;
+ }
+ buffer->ptr = mallocBuf;
+ buffer->direct = 0;
+ ret = 0;
+
+done:
+ free(mallocBuf);
+ (*env)->DeleteLocalRef(env, array);
+ return ret;
+}
+
+static int translateZCRException(JNIEnv *env, jthrowable exc)
+{
+ int ret;
+ char *className = NULL;
+ jthrowable jthr = classNameOfObject(exc, env, &className);
+
+ if (jthr) {
+ fputs("hadoopReadZero: failed to get class name of "
+ "exception from read().\n", stderr);
+ destroyLocalReference(env, exc);
+ destroyLocalReference(env, jthr);
+ ret = EIO;
+ goto done;
+ }
+ if (!strcmp(className, "java.lang.UnsupportedOperationException")) {
+ ret = EPROTONOSUPPORT;
+ goto done;
+ }
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hadoopZeroCopyRead: ZeroCopyCursor#read failed");
+done:
+ free(className);
+ return ret;
+}
+
+struct hadoopRzBuffer* hadoopReadZero(hdfsFile file,
+ struct hadoopRzOptions *opts, int32_t maxLength)
+{
+ JNIEnv *env;
+ jthrowable jthr = NULL;
+ jvalue jVal;
+ jobject enumSet = NULL, byteBuffer = NULL;
+ struct hadoopRzBuffer* buffer = NULL;
+ int ret;
+
+ env = getJNIEnv();
+ if (!env) {
+ errno = EINTERNAL;
+ return NULL;
+ }
+ if (file->type != HDFS_STREAM_INPUT) {
+ fputs("Cannot read from a non-InputStream object!\n", stderr);
+ ret = EINVAL;
+ goto done;
+ }
+ buffer = calloc(1, sizeof(struct hadoopRzBuffer));
+ if (!buffer) {
+ ret = ENOMEM;
+ goto done;
+ }
+ jthr = hadoopRzOptionsGetEnumSet(env, opts, &enumSet);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hadoopReadZero: hadoopRzOptionsGetEnumSet failed: ");
+ goto done;
+ }
+ jthr = invokeMethod(env, &jVal, INSTANCE, file->file, HADOOP_ISTRM, "read",
+ "(Lorg/apache/hadoop/io/ByteBufferPool;ILjava/util/EnumSet;)"
+ "Ljava/nio/ByteBuffer;", opts->byteBufferPool, maxLength, enumSet);
+ if (jthr) {
+ ret = translateZCRException(env, jthr);
+ goto done;
+ }
+ byteBuffer = jVal.l;
+ if (!byteBuffer) {
+ buffer->byteBuffer = NULL;
+ buffer->length = 0;
+ buffer->ptr = NULL;
+ } else {
+ buffer->byteBuffer = (*env)->NewGlobalRef(env, byteBuffer);
+ if (!buffer->byteBuffer) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hadoopReadZero: failed to create global ref to ByteBuffer");
+ goto done;
+ }
+ ret = hadoopReadZeroExtractBuffer(env, opts, buffer);
+ if (ret) {
+ goto done;
+ }
+ }
+ ret = 0;
+done:
+ (*env)->DeleteLocalRef(env, byteBuffer);
+ if (ret) {
+ if (buffer) {
+ if (buffer->byteBuffer) {
+ (*env)->DeleteGlobalRef(env, buffer->byteBuffer);
+ }
+ free(buffer);
+ }
+ errno = ret;
+ return NULL;
+ } else {
+ errno = 0;
+ }
+ return buffer;
+}
+
+int32_t hadoopRzBufferLength(const struct hadoopRzBuffer *buffer)
+{
+ return buffer->length;
+}
+
+const void *hadoopRzBufferGet(const struct hadoopRzBuffer *buffer)
+{
+ return buffer->ptr;
+}
+
+void hadoopRzBufferFree(hdfsFile file, struct hadoopRzBuffer *buffer)
+{
+ jvalue jVal;
+ jthrowable jthr;
+ JNIEnv* env;
+
+ env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return;
+ }
+ if (buffer->byteBuffer) {
+ jthr = invokeMethod(env, &jVal, INSTANCE, file->file,
+ HADOOP_ISTRM, "releaseBuffer",
+ "(Ljava/nio/ByteBuffer;)V", buffer->byteBuffer);
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hadoopRzBufferFree: releaseBuffer failed: ");
+ // even on error, we have to delete the reference.
+ }
+ (*env)->DeleteGlobalRef(env, buffer->byteBuffer);
+ }
+ if (!buffer->direct) {
+ free(buffer->ptr);
+ }
+ memset(buffer, 0, sizeof(*buffer));
+ free(buffer);
+}
+
+char***
+hdfsGetHosts(hdfsFS fs, const char *path, tOffset start, tOffset length)
+{
+ // JAVA EQUIVALENT:
+ // fs.getFileBlockLoctions(new Path(path), start, length);
+
+ jobject jFS = (jobject)fs;
+ jthrowable jthr;
+ jobject jPath = NULL;
+ jobject jFileStatus = NULL;
+ jvalue jFSVal, jVal;
+ jobjectArray jBlockLocations = NULL, jFileBlockHosts = NULL;
+ jstring jHost = NULL;
+ char*** blockHosts = NULL;
+ int i, j, ret;
+ jsize jNumFileBlocks = 0;
+ jobject jFileBlock;
+ jsize jNumBlockHosts;
+ const char *hostName;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return NULL;
+ }
+
+ //Create an object of org.apache.hadoop.fs.Path
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetHosts(path=%s): constructNewObjectOfPath", path);
+ goto done;
+ }
+ jthr = invokeMethod(env, &jFSVal, INSTANCE, jFS,
+ HADOOP_FS, "getFileStatus", "(Lorg/apache/hadoop/fs/Path;)"
+ "Lorg/apache/hadoop/fs/FileStatus;", jPath);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, NOPRINT_EXC_FILE_NOT_FOUND,
+ "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
+ "FileSystem#getFileStatus", path, start, length);
+ destroyLocalReference(env, jPath);
+ goto done;
+ }
+ jFileStatus = jFSVal.l;
+
+ //org.apache.hadoop.fs.FileSystem#getFileBlockLocations
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS,
+ HADOOP_FS, "getFileBlockLocations",
+ "(Lorg/apache/hadoop/fs/FileStatus;JJ)"
+ "[Lorg/apache/hadoop/fs/BlockLocation;",
+ jFileStatus, start, length);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
+ "FileSystem#getFileBlockLocations", path, start, length);
+ goto done;
+ }
+ jBlockLocations = jVal.l;
+
+ //Figure out no of entries in jBlockLocations
+ //Allocate memory and add NULL at the end
+ jNumFileBlocks = (*env)->GetArrayLength(env, jBlockLocations);
+
+ blockHosts = calloc(jNumFileBlocks + 1, sizeof(char**));
+ if (blockHosts == NULL) {
+ ret = ENOMEM;
+ goto done;
+ }
+ if (jNumFileBlocks == 0) {
+ ret = 0;
+ goto done;
+ }
+
+ //Now parse each block to get hostnames
+ for (i = 0; i < jNumFileBlocks; ++i) {
+ jFileBlock =
+ (*env)->GetObjectArrayElement(env, jBlockLocations, i);
+ if (!jFileBlock) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
+ "GetObjectArrayElement(%d)", path, start, length, i);
+ goto done;
+ }
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFileBlock, HADOOP_BLK_LOC,
+ "getHosts", "()[Ljava/lang/String;");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
+ "BlockLocation#getHosts", path, start, length);
+ goto done;
+ }
+ jFileBlockHosts = jVal.l;
+ if (!jFileBlockHosts) {
+ fprintf(stderr,
+ "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
+ "BlockLocation#getHosts returned NULL", path, start, length);
+ ret = EINTERNAL;
+ goto done;
+ }
+ //Figure out no of hosts in jFileBlockHosts, and allocate the memory
+ jNumBlockHosts = (*env)->GetArrayLength(env, jFileBlockHosts);
+ blockHosts[i] = calloc(jNumBlockHosts + 1, sizeof(char*));
+ if (!blockHosts[i]) {
+ ret = ENOMEM;
+ goto done;
+ }
+
+ //Now parse each hostname
+ for (j = 0; j < jNumBlockHosts; ++j) {
+ jHost = (*env)->GetObjectArrayElement(env, jFileBlockHosts, j);
+ if (!jHost) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"): "
+ "NewByteArray", path, start, length);
+ goto done;
+ }
+ hostName =
+ (const char*)((*env)->GetStringUTFChars(env, jHost, NULL));
+ if (!hostName) {
+ ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64", "
+ "j=%d out of %d): GetStringUTFChars",
+ path, start, length, j, jNumBlockHosts);
+ goto done;
+ }
+ blockHosts[i][j] = strdup(hostName);
+ (*env)->ReleaseStringUTFChars(env, jHost, hostName);
+ if (!blockHosts[i][j]) {
+ ret = ENOMEM;
+ goto done;
+ }
+ destroyLocalReference(env, jHost);
+ jHost = NULL;
+ }
+
+ destroyLocalReference(env, jFileBlockHosts);
+ jFileBlockHosts = NULL;
+ }
+ ret = 0;
+
+done:
+ destroyLocalReference(env, jPath);
+ destroyLocalReference(env, jFileStatus);
+ destroyLocalReference(env, jBlockLocations);
+ destroyLocalReference(env, jFileBlockHosts);
+ destroyLocalReference(env, jHost);
+ if (ret) {
+ if (blockHosts) {
+ hdfsFreeHosts(blockHosts);
+ }
+ return NULL;
+ }
+
+ return blockHosts;
+}
+
+
+void hdfsFreeHosts(char ***blockHosts)
+{
+ int i, j;
+ for (i=0; blockHosts[i]; i++) {
+ for (j=0; blockHosts[i][j]; j++) {
+ free(blockHosts[i][j]);
+ }
+ free(blockHosts[i]);
+ }
+ free(blockHosts);
+}
+
+
+tOffset hdfsGetDefaultBlockSize(hdfsFS fs)
+{
+ // JAVA EQUIVALENT:
+ // fs.getDefaultBlockSize();
+
+ jobject jFS = (jobject)fs;
+ jvalue jVal;
+ jthrowable jthr;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //FileSystem#getDefaultBlockSize()
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "getDefaultBlockSize", "()J");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetDefaultBlockSize: FileSystem#getDefaultBlockSize");
+ return -1;
+ }
+ return jVal.j;
+}
+
+
+tOffset hdfsGetDefaultBlockSizeAtPath(hdfsFS fs, const char *path)
+{
+ // JAVA EQUIVALENT:
+ // fs.getDefaultBlockSize(path);
+
+ jthrowable jthr;
+ jobject jFS = (jobject)fs;
+ jobject jPath;
+ tOffset blockSize;
+ JNIEnv* env = getJNIEnv();
+
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+ jthr = constructNewObjectOfPath(env, path, &jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetDefaultBlockSize(path=%s): constructNewObjectOfPath",
+ path);
+ return -1;
+ }
+ jthr = getDefaultBlockSize(env, jFS, jPath, &blockSize);
+ (*env)->DeleteLocalRef(env, jPath);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetDefaultBlockSize(path=%s): "
+ "FileSystem#getDefaultBlockSize", path);
+ return -1;
+ }
+ return blockSize;
+}
+
+
+tOffset hdfsGetCapacity(hdfsFS fs)
+{
+ // JAVA EQUIVALENT:
+ // FsStatus fss = fs.getStatus();
+ // return Fss.getCapacity();
+
+ jobject jFS = (jobject)fs;
+ jvalue jVal;
+ jthrowable jthr;
+ jobject fss;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //FileSystem#getStatus
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "getStatus", "()Lorg/apache/hadoop/fs/FsStatus;");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetCapacity: FileSystem#getStatus");
+ return -1;
+ }
+ fss = (jobject)jVal.l;
+ jthr = invokeMethod(env, &jVal, INSTANCE, fss, HADOOP_FSSTATUS,
+ "getCapacity", "()J");
+ destroyLocalReference(env, fss);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetCapacity: FsStatus#getCapacity");
+ return -1;
+ }
+ return jVal.j;
+}
+
+
+
+tOffset hdfsGetUsed(hdfsFS fs)
+{
+ // JAVA EQUIVALENT:
+ // FsStatus fss = fs.getStatus();
+ // return Fss.getUsed();
+
+ jobject jFS = (jobject)fs;
+ jvalue jVal;
+ jthrowable jthr;
+ jobject fss;
+
+ //Get the JNIEnv* corresponding to current thread
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+
+ //FileSystem#getStatus
+ jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
+ "getStatus", "()Lorg/apache/hadoop/fs/FsStatus;");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetUsed: FileSystem#getStatus");
+ return -1;
+ }
+ fss = (jobject)jVal.l;
+ jthr = invokeMethod(env, &jVal, INSTANCE, fss, HADOOP_FSSTATUS,
+ "getUsed", "()J");
+ destroyLocalReference(env, fss);
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsGetUsed: FsStatus#getUsed");
+ return -1;
+ }
+ return jVal.j;
+}
+
+/**
+ * We cannot add new fields to the hdfsFileInfo structure because it would break
+ * binary compatibility. The reason is because we return an array
+ * of hdfsFileInfo structures from hdfsListDirectory. So changing the size of
+ * those structures would break all programs that relied on finding the second
+ * element in the array at <base_offset> + sizeof(struct hdfsFileInfo).
+ *
+ * So instead, we add the new fields to the hdfsExtendedFileInfo structure.
+ * This structure is contained in the mOwner string found inside the
+ * hdfsFileInfo. Specifically, the format of mOwner is:
+ *
+ * [owner-string] [null byte] [padding] [hdfsExtendedFileInfo structure]
+ *
+ * The padding is added so that the hdfsExtendedFileInfo structure starts on an
+ * 8-byte boundary.
+ *
+ * @param str The string to locate the extended info in.
+ * @return The offset of the hdfsExtendedFileInfo structure.
+ */
+static size_t getExtendedFileInfoOffset(const char *str)
+{
+
<TRUNCATED>
[26/35] hadoop git commit: HDFS-9178. Slow datanode I/O can cause a
wrong node to be marked bad. Contributed by Kihwal Lee.
Posted by ji...@apache.org.
HDFS-9178. Slow datanode I/O can cause a wrong node to be marked bad. Contributed by Kihwal Lee.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/99e5204f
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/99e5204f
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/99e5204f
Branch: refs/heads/HDFS-8966
Commit: 99e5204ff5326430558b6f6fd9da7c44654c15d7
Parents: 61b3547
Author: Kihwal Lee <ki...@apache.org>
Authored: Wed Oct 7 10:17:17 2015 -0500
Committer: Kihwal Lee <ki...@apache.org>
Committed: Wed Oct 7 10:17:17 2015 -0500
----------------------------------------------------------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +
.../hdfs/server/datanode/BlockReceiver.java | 52 +++++++++++++++-
.../server/datanode/DataNodeFaultInjector.java | 8 +++
.../TestClientProtocolForPipelineRecovery.java | 63 ++++++++++++++++++++
4 files changed, 124 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/99e5204f/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index e495497..33a78f0 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2028,6 +2028,9 @@ Release 2.7.2 - UNRELEASED
pool to be scanned but there are suspicious blocks. (Colin Patrick McCabe
via yliu)
+ HDFS-9178. Slow datanode I/O can cause a wrong node to be marked bad
+ (kihwal)
+
Release 2.7.1 - 2015-07-06
INCOMPATIBLE CHANGES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/99e5204f/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java
index eec2b2d..4c40e83 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java
@@ -23,6 +23,7 @@ import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
+import java.io.EOFException;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -136,6 +137,8 @@ class BlockReceiver implements Closeable {
private DataOutputStream replyOut = null;
private boolean pinning;
+ private long lastSentTime;
+ private long maxSendIdleTime;
BlockReceiver(final ExtendedBlock block, final StorageType storageType,
final DataInputStream in,
@@ -162,7 +165,8 @@ class BlockReceiver implements Closeable {
this.datanodeSlowLogThresholdMs = datanode.getDnConf().datanodeSlowIoWarningThresholdMs;
// For replaceBlock() calls response should be sent to avoid socketTimeout
// at clients. So sending with the interval of 0.5 * socketTimeout
- this.responseInterval = (long) (datanode.getDnConf().socketTimeout * 0.5);
+ final long readTimeout = datanode.getDnConf().socketTimeout;
+ this.responseInterval = (long) (readTimeout * 0.5);
//for datanode, we have
//1: clientName.length() == 0, and
//2: stage == null or PIPELINE_SETUP_CREATE
@@ -171,6 +175,12 @@ class BlockReceiver implements Closeable {
|| stage == BlockConstructionStage.TRANSFER_FINALIZED;
this.pinning = pinning;
+ this.lastSentTime = Time.monotonicNow();
+ // Downstream will timeout in readTimeout on receiving the next packet.
+ // If there is no data traffic, a heartbeat packet is sent at
+ // the interval of 0.5*readTimeout. Here, we set 0.9*readTimeout to be
+ // the threshold for detecting congestion.
+ this.maxSendIdleTime = (long) (readTimeout * 0.9);
if (LOG.isDebugEnabled()) {
LOG.debug(getClass().getSimpleName() + ": " + block
+ "\n isClient =" + isClient + ", clientname=" + clientname
@@ -357,6 +367,25 @@ class BlockReceiver implements Closeable {
}
}
+ synchronized void setLastSentTime(long sentTime) {
+ lastSentTime = sentTime;
+ }
+
+ /**
+ * It can return false if
+ * - upstream did not send packet for a long time
+ * - a packet was received but got stuck in local disk I/O.
+ * - a packet was received but got stuck on send to mirror.
+ */
+ synchronized boolean packetSentInTime() {
+ long diff = Time.monotonicNow() - lastSentTime;
+ if (diff > maxSendIdleTime) {
+ LOG.info("A packet was last sent " + diff + " milliseconds ago.");
+ return false;
+ }
+ return true;
+ }
+
/**
* Flush block data and metadata files to disk.
* @throws IOException
@@ -520,13 +549,21 @@ class BlockReceiver implements Closeable {
lastPacketInBlock, offsetInBlock, Status.SUCCESS);
}
+ // Drop heartbeat for testing.
+ if (seqno < 0 && len == 0 &&
+ DataNodeFaultInjector.get().dropHeartbeatPacket()) {
+ return 0;
+ }
+
//First write the packet to the mirror:
if (mirrorOut != null && !mirrorError) {
try {
long begin = Time.monotonicNow();
packetReceiver.mirrorPacketTo(mirrorOut);
mirrorOut.flush();
- long duration = Time.monotonicNow() - begin;
+ long now = Time.monotonicNow();
+ setLastSentTime(now);
+ long duration = now - begin;
if (duration > datanodeSlowLogThresholdMs) {
LOG.warn("Slow BlockReceiver write packet to mirror took " + duration
+ "ms (threshold=" + datanodeSlowLogThresholdMs + "ms)");
@@ -1296,6 +1333,17 @@ class BlockReceiver implements Closeable {
} catch (IOException ioe) {
if (Thread.interrupted()) {
isInterrupted = true;
+ } else if (ioe instanceof EOFException && !packetSentInTime()) {
+ // The downstream error was caused by upstream including this
+ // node not sending packet in time. Let the upstream determine
+ // who is at fault. If the immediate upstream node thinks it
+ // has sent a packet in time, this node will be reported as bad.
+ // Otherwise, the upstream node will propagate the error up by
+ // closing the connection.
+ LOG.warn("The downstream error might be due to congestion in " +
+ "upstream including this node. Propagating the error: ",
+ ioe);
+ throw ioe;
} else {
// continue to run even if can not read from mirror
// notify client of the error
http://git-wip-us.apache.org/repos/asf/hadoop/blob/99e5204f/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNodeFaultInjector.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNodeFaultInjector.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNodeFaultInjector.java
index 65f0506..46ec3ae 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNodeFaultInjector.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNodeFaultInjector.java
@@ -36,9 +36,17 @@ public class DataNodeFaultInjector {
return instance;
}
+ public static void set(DataNodeFaultInjector injector) {
+ instance = injector;
+ }
+
public void getHdfsBlocksMetadata() {}
public void writeBlockAfterFlush() throws IOException {}
public void sendShortCircuitShmResponse() throws IOException {}
+
+ public boolean dropHeartbeatPacket() {
+ return false;
+ }
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/99e5204f/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestClientProtocolForPipelineRecovery.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestClientProtocolForPipelineRecovery.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestClientProtocolForPipelineRecovery.java
index b83157d..77cfb7c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestClientProtocolForPipelineRecovery.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestClientProtocolForPipelineRecovery.java
@@ -21,11 +21,14 @@ import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
+import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
+import org.apache.hadoop.hdfs.server.datanode.DataNodeFaultInjector;
import org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.hdfs.tools.DFSAdmin;
@@ -160,6 +163,66 @@ public class TestClientProtocolForPipelineRecovery {
}
}
+ @Test
+ public void testPacketTransmissionDelay() throws Exception {
+ // Make the first datanode to not relay heartbeat packet.
+ DataNodeFaultInjector dnFaultInjector = new DataNodeFaultInjector() {
+ @Override
+ public boolean dropHeartbeatPacket() {
+ return true;
+ }
+ };
+ DataNodeFaultInjector oldDnInjector = DataNodeFaultInjector.get();
+ DataNodeFaultInjector.set(dnFaultInjector);
+
+ // Setting the timeout to be 3 seconds. Normally heartbeat packet
+ // would be sent every 1.5 seconds if there is no data traffic.
+ Configuration conf = new HdfsConfiguration();
+ conf.set(HdfsClientConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY, "3000");
+ MiniDFSCluster cluster = null;
+
+ try {
+ int numDataNodes = 2;
+ cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDataNodes).build();
+ cluster.waitActive();
+ FileSystem fs = cluster.getFileSystem();
+
+ FSDataOutputStream out = fs.create(new Path("noheartbeat.dat"), (short)2);
+ out.write(0x31);
+ out.hflush();
+
+ DFSOutputStream dfsOut = (DFSOutputStream)out.getWrappedStream();
+
+ // original pipeline
+ DatanodeInfo[] orgNodes = dfsOut.getPipeline();
+
+ // Cause the second datanode to timeout on reading packet
+ Thread.sleep(3500);
+ out.write(0x32);
+ out.hflush();
+
+ // new pipeline
+ DatanodeInfo[] newNodes = dfsOut.getPipeline();
+ out.close();
+
+ boolean contains = false;
+ for (int i = 0; i < newNodes.length; i++) {
+ if (orgNodes[0].getXferAddr().equals(newNodes[i].getXferAddr())) {
+ throw new IOException("The first datanode should have been replaced.");
+ }
+ if (orgNodes[1].getXferAddr().equals(newNodes[i].getXferAddr())) {
+ contains = true;
+ }
+ }
+ Assert.assertTrue(contains);
+ } finally {
+ DataNodeFaultInjector.set(oldDnInjector);
+ if (cluster != null) {
+ cluster.shutdown();
+ }
+ }
+ }
+
/**
* Test recovery on restart OOB message. It also tests the delivery of
* OOB ack originating from the primary datanode. Since there is only
[09/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs.c
deleted file mode 100644
index a3769fc..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs.c
+++ /dev/null
@@ -1,3342 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "exception.h"
-#include "hdfs.h"
-#include "jni_helper.h"
-#include "platform.h"
-
-#include <fcntl.h>
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-
-/* Some frequently used Java paths */
-#define HADOOP_CONF "org/apache/hadoop/conf/Configuration"
-#define HADOOP_PATH "org/apache/hadoop/fs/Path"
-#define HADOOP_LOCALFS "org/apache/hadoop/fs/LocalFileSystem"
-#define HADOOP_FS "org/apache/hadoop/fs/FileSystem"
-#define HADOOP_FSSTATUS "org/apache/hadoop/fs/FsStatus"
-#define HADOOP_BLK_LOC "org/apache/hadoop/fs/BlockLocation"
-#define HADOOP_DFS "org/apache/hadoop/hdfs/DistributedFileSystem"
-#define HADOOP_ISTRM "org/apache/hadoop/fs/FSDataInputStream"
-#define HADOOP_OSTRM "org/apache/hadoop/fs/FSDataOutputStream"
-#define HADOOP_STAT "org/apache/hadoop/fs/FileStatus"
-#define HADOOP_FSPERM "org/apache/hadoop/fs/permission/FsPermission"
-#define JAVA_NET_ISA "java/net/InetSocketAddress"
-#define JAVA_NET_URI "java/net/URI"
-#define JAVA_STRING "java/lang/String"
-#define READ_OPTION "org/apache/hadoop/fs/ReadOption"
-
-#define JAVA_VOID "V"
-
-/* Macros for constructing method signatures */
-#define JPARAM(X) "L" X ";"
-#define JARRPARAM(X) "[L" X ";"
-#define JMETHOD1(X, R) "(" X ")" R
-#define JMETHOD2(X, Y, R) "(" X Y ")" R
-#define JMETHOD3(X, Y, Z, R) "(" X Y Z")" R
-
-#define KERBEROS_TICKET_CACHE_PATH "hadoop.security.kerberos.ticket.cache.path"
-
-// Bit fields for hdfsFile_internal flags
-#define HDFS_FILE_SUPPORTS_DIRECT_READ (1<<0)
-
-tSize readDirect(hdfsFS fs, hdfsFile f, void* buffer, tSize length);
-static void hdfsFreeFileInfoEntry(hdfsFileInfo *hdfsFileInfo);
-
-/**
- * The C equivalent of org.apache.org.hadoop.FSData(Input|Output)Stream .
- */
-enum hdfsStreamType
-{
- HDFS_STREAM_UNINITIALIZED = 0,
- HDFS_STREAM_INPUT = 1,
- HDFS_STREAM_OUTPUT = 2,
-};
-
-/**
- * The 'file-handle' to a file in hdfs.
- */
-struct hdfsFile_internal {
- void* file;
- enum hdfsStreamType type;
- int flags;
-};
-
-#define HDFS_EXTENDED_FILE_INFO_ENCRYPTED 0x1
-
-/**
- * Extended file information.
- */
-struct hdfsExtendedFileInfo {
- int flags;
-};
-
-int hdfsFileIsOpenForRead(hdfsFile file)
-{
- return (file->type == HDFS_STREAM_INPUT);
-}
-
-int hdfsFileGetReadStatistics(hdfsFile file,
- struct hdfsReadStatistics **stats)
-{
- jthrowable jthr;
- jobject readStats = NULL;
- jvalue jVal;
- struct hdfsReadStatistics *s = NULL;
- int ret;
- JNIEnv* env = getJNIEnv();
-
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
- if (file->type != HDFS_STREAM_INPUT) {
- ret = EINVAL;
- goto done;
- }
- jthr = invokeMethod(env, &jVal, INSTANCE, file->file,
- "org/apache/hadoop/hdfs/client/HdfsDataInputStream",
- "getReadStatistics",
- "()Lorg/apache/hadoop/hdfs/DFSInputStream$ReadStatistics;");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsFileGetReadStatistics: getReadStatistics failed");
- goto done;
- }
- readStats = jVal.l;
- s = malloc(sizeof(struct hdfsReadStatistics));
- if (!s) {
- ret = ENOMEM;
- goto done;
- }
- jthr = invokeMethod(env, &jVal, INSTANCE, readStats,
- "org/apache/hadoop/hdfs/DFSInputStream$ReadStatistics",
- "getTotalBytesRead", "()J");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsFileGetReadStatistics: getTotalBytesRead failed");
- goto done;
- }
- s->totalBytesRead = jVal.j;
-
- jthr = invokeMethod(env, &jVal, INSTANCE, readStats,
- "org/apache/hadoop/hdfs/DFSInputStream$ReadStatistics",
- "getTotalLocalBytesRead", "()J");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsFileGetReadStatistics: getTotalLocalBytesRead failed");
- goto done;
- }
- s->totalLocalBytesRead = jVal.j;
-
- jthr = invokeMethod(env, &jVal, INSTANCE, readStats,
- "org/apache/hadoop/hdfs/DFSInputStream$ReadStatistics",
- "getTotalShortCircuitBytesRead", "()J");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsFileGetReadStatistics: getTotalShortCircuitBytesRead failed");
- goto done;
- }
- s->totalShortCircuitBytesRead = jVal.j;
- jthr = invokeMethod(env, &jVal, INSTANCE, readStats,
- "org/apache/hadoop/hdfs/DFSInputStream$ReadStatistics",
- "getTotalZeroCopyBytesRead", "()J");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsFileGetReadStatistics: getTotalZeroCopyBytesRead failed");
- goto done;
- }
- s->totalZeroCopyBytesRead = jVal.j;
- *stats = s;
- s = NULL;
- ret = 0;
-
-done:
- destroyLocalReference(env, readStats);
- free(s);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int64_t hdfsReadStatisticsGetRemoteBytesRead(
- const struct hdfsReadStatistics *stats)
-{
- return stats->totalBytesRead - stats->totalLocalBytesRead;
-}
-
-int hdfsFileClearReadStatistics(hdfsFile file)
-{
- jthrowable jthr;
- int ret;
- JNIEnv* env = getJNIEnv();
-
- if (env == NULL) {
- errno = EINTERNAL;
- return EINTERNAL;
- }
- if (file->type != HDFS_STREAM_INPUT) {
- ret = EINVAL;
- goto done;
- }
- jthr = invokeMethod(env, NULL, INSTANCE, file->file,
- "org/apache/hadoop/hdfs/client/HdfsDataInputStream",
- "clearReadStatistics", "()V");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsFileClearReadStatistics: clearReadStatistics failed");
- goto done;
- }
- ret = 0;
-done:
- if (ret) {
- errno = ret;
- return ret;
- }
- return 0;
-}
-
-void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats)
-{
- free(stats);
-}
-
-int hdfsFileIsOpenForWrite(hdfsFile file)
-{
- return (file->type == HDFS_STREAM_OUTPUT);
-}
-
-int hdfsFileUsesDirectRead(hdfsFile file)
-{
- return !!(file->flags & HDFS_FILE_SUPPORTS_DIRECT_READ);
-}
-
-void hdfsFileDisableDirectRead(hdfsFile file)
-{
- file->flags &= ~HDFS_FILE_SUPPORTS_DIRECT_READ;
-}
-
-int hdfsDisableDomainSocketSecurity(void)
-{
- jthrowable jthr;
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
- jthr = invokeMethod(env, NULL, STATIC, NULL,
- "org/apache/hadoop/net/unix/DomainSocket",
- "disableBindPathValidation", "()V");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "DomainSocket#disableBindPathValidation");
- return -1;
- }
- return 0;
-}
-
-/**
- * hdfsJniEnv: A wrapper struct to be used as 'value'
- * while saving thread -> JNIEnv* mappings
- */
-typedef struct
-{
- JNIEnv* env;
-} hdfsJniEnv;
-
-/**
- * Helper function to create a org.apache.hadoop.fs.Path object.
- * @param env: The JNIEnv pointer.
- * @param path: The file-path for which to construct org.apache.hadoop.fs.Path
- * object.
- * @return Returns a jobject on success and NULL on error.
- */
-static jthrowable constructNewObjectOfPath(JNIEnv *env, const char *path,
- jobject *out)
-{
- jthrowable jthr;
- jstring jPathString;
- jobject jPath;
-
- //Construct a java.lang.String object
- jthr = newJavaStr(env, path, &jPathString);
- if (jthr)
- return jthr;
- //Construct the org.apache.hadoop.fs.Path object
- jthr = constructNewObjectOfClass(env, &jPath, "org/apache/hadoop/fs/Path",
- "(Ljava/lang/String;)V", jPathString);
- destroyLocalReference(env, jPathString);
- if (jthr)
- return jthr;
- *out = jPath;
- return NULL;
-}
-
-static jthrowable hadoopConfGetStr(JNIEnv *env, jobject jConfiguration,
- const char *key, char **val)
-{
- jthrowable jthr;
- jvalue jVal;
- jstring jkey = NULL, jRet = NULL;
-
- jthr = newJavaStr(env, key, &jkey);
- if (jthr)
- goto done;
- jthr = invokeMethod(env, &jVal, INSTANCE, jConfiguration,
- HADOOP_CONF, "get", JMETHOD1(JPARAM(JAVA_STRING),
- JPARAM(JAVA_STRING)), jkey);
- if (jthr)
- goto done;
- jRet = jVal.l;
- jthr = newCStr(env, jRet, val);
-done:
- destroyLocalReference(env, jkey);
- destroyLocalReference(env, jRet);
- return jthr;
-}
-
-int hdfsConfGetStr(const char *key, char **val)
-{
- JNIEnv *env;
- int ret;
- jthrowable jthr;
- jobject jConfiguration = NULL;
-
- env = getJNIEnv();
- if (env == NULL) {
- ret = EINTERNAL;
- goto done;
- }
- jthr = constructNewObjectOfClass(env, &jConfiguration, HADOOP_CONF, "()V");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsConfGetStr(%s): new Configuration", key);
- goto done;
- }
- jthr = hadoopConfGetStr(env, jConfiguration, key, val);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsConfGetStr(%s): hadoopConfGetStr", key);
- goto done;
- }
- ret = 0;
-done:
- destroyLocalReference(env, jConfiguration);
- if (ret)
- errno = ret;
- return ret;
-}
-
-void hdfsConfStrFree(char *val)
-{
- free(val);
-}
-
-static jthrowable hadoopConfGetInt(JNIEnv *env, jobject jConfiguration,
- const char *key, int32_t *val)
-{
- jthrowable jthr = NULL;
- jvalue jVal;
- jstring jkey = NULL;
-
- jthr = newJavaStr(env, key, &jkey);
- if (jthr)
- return jthr;
- jthr = invokeMethod(env, &jVal, INSTANCE, jConfiguration,
- HADOOP_CONF, "getInt", JMETHOD2(JPARAM(JAVA_STRING), "I", "I"),
- jkey, (jint)(*val));
- destroyLocalReference(env, jkey);
- if (jthr)
- return jthr;
- *val = jVal.i;
- return NULL;
-}
-
-int hdfsConfGetInt(const char *key, int32_t *val)
-{
- JNIEnv *env;
- int ret;
- jobject jConfiguration = NULL;
- jthrowable jthr;
-
- env = getJNIEnv();
- if (env == NULL) {
- ret = EINTERNAL;
- goto done;
- }
- jthr = constructNewObjectOfClass(env, &jConfiguration, HADOOP_CONF, "()V");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsConfGetInt(%s): new Configuration", key);
- goto done;
- }
- jthr = hadoopConfGetInt(env, jConfiguration, key, val);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsConfGetInt(%s): hadoopConfGetInt", key);
- goto done;
- }
- ret = 0;
-done:
- destroyLocalReference(env, jConfiguration);
- if (ret)
- errno = ret;
- return ret;
-}
-
-struct hdfsBuilderConfOpt {
- struct hdfsBuilderConfOpt *next;
- const char *key;
- const char *val;
-};
-
-struct hdfsBuilder {
- int forceNewInstance;
- const char *nn;
- tPort port;
- const char *kerbTicketCachePath;
- const char *userName;
- struct hdfsBuilderConfOpt *opts;
-};
-
-struct hdfsBuilder *hdfsNewBuilder(void)
-{
- struct hdfsBuilder *bld = calloc(1, sizeof(struct hdfsBuilder));
- if (!bld) {
- errno = ENOMEM;
- return NULL;
- }
- return bld;
-}
-
-int hdfsBuilderConfSetStr(struct hdfsBuilder *bld, const char *key,
- const char *val)
-{
- struct hdfsBuilderConfOpt *opt, *next;
-
- opt = calloc(1, sizeof(struct hdfsBuilderConfOpt));
- if (!opt)
- return -ENOMEM;
- next = bld->opts;
- bld->opts = opt;
- opt->next = next;
- opt->key = key;
- opt->val = val;
- return 0;
-}
-
-void hdfsFreeBuilder(struct hdfsBuilder *bld)
-{
- struct hdfsBuilderConfOpt *cur, *next;
-
- cur = bld->opts;
- for (cur = bld->opts; cur; ) {
- next = cur->next;
- free(cur);
- cur = next;
- }
- free(bld);
-}
-
-void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld)
-{
- bld->forceNewInstance = 1;
-}
-
-void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn)
-{
- bld->nn = nn;
-}
-
-void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port)
-{
- bld->port = port;
-}
-
-void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName)
-{
- bld->userName = userName;
-}
-
-void hdfsBuilderSetKerbTicketCachePath(struct hdfsBuilder *bld,
- const char *kerbTicketCachePath)
-{
- bld->kerbTicketCachePath = kerbTicketCachePath;
-}
-
-hdfsFS hdfsConnect(const char *host, tPort port)
-{
- struct hdfsBuilder *bld = hdfsNewBuilder();
- if (!bld)
- return NULL;
- hdfsBuilderSetNameNode(bld, host);
- hdfsBuilderSetNameNodePort(bld, port);
- return hdfsBuilderConnect(bld);
-}
-
-/** Always return a new FileSystem handle */
-hdfsFS hdfsConnectNewInstance(const char *host, tPort port)
-{
- struct hdfsBuilder *bld = hdfsNewBuilder();
- if (!bld)
- return NULL;
- hdfsBuilderSetNameNode(bld, host);
- hdfsBuilderSetNameNodePort(bld, port);
- hdfsBuilderSetForceNewInstance(bld);
- return hdfsBuilderConnect(bld);
-}
-
-hdfsFS hdfsConnectAsUser(const char *host, tPort port, const char *user)
-{
- struct hdfsBuilder *bld = hdfsNewBuilder();
- if (!bld)
- return NULL;
- hdfsBuilderSetNameNode(bld, host);
- hdfsBuilderSetNameNodePort(bld, port);
- hdfsBuilderSetUserName(bld, user);
- return hdfsBuilderConnect(bld);
-}
-
-/** Always return a new FileSystem handle */
-hdfsFS hdfsConnectAsUserNewInstance(const char *host, tPort port,
- const char *user)
-{
- struct hdfsBuilder *bld = hdfsNewBuilder();
- if (!bld)
- return NULL;
- hdfsBuilderSetNameNode(bld, host);
- hdfsBuilderSetNameNodePort(bld, port);
- hdfsBuilderSetForceNewInstance(bld);
- hdfsBuilderSetUserName(bld, user);
- return hdfsBuilderConnect(bld);
-}
-
-
-/**
- * Calculate the effective URI to use, given a builder configuration.
- *
- * If there is not already a URI scheme, we prepend 'hdfs://'.
- *
- * If there is not already a port specified, and a port was given to the
- * builder, we suffix that port. If there is a port specified but also one in
- * the URI, that is an error.
- *
- * @param bld The hdfs builder object
- * @param uri (out param) dynamically allocated string representing the
- * effective URI
- *
- * @return 0 on success; error code otherwise
- */
-static int calcEffectiveURI(struct hdfsBuilder *bld, char ** uri)
-{
- const char *scheme;
- char suffix[64];
- const char *lastColon;
- char *u;
- size_t uriLen;
-
- if (!bld->nn)
- return EINVAL;
- scheme = (strstr(bld->nn, "://")) ? "" : "hdfs://";
- if (bld->port == 0) {
- suffix[0] = '\0';
- } else {
- lastColon = strrchr(bld->nn, ':');
- if (lastColon && (strspn(lastColon + 1, "0123456789") ==
- strlen(lastColon + 1))) {
- fprintf(stderr, "port %d was given, but URI '%s' already "
- "contains a port!\n", bld->port, bld->nn);
- return EINVAL;
- }
- snprintf(suffix, sizeof(suffix), ":%d", bld->port);
- }
-
- uriLen = strlen(scheme) + strlen(bld->nn) + strlen(suffix);
- u = malloc((uriLen + 1) * (sizeof(char)));
- if (!u) {
- fprintf(stderr, "calcEffectiveURI: out of memory");
- return ENOMEM;
- }
- snprintf(u, uriLen + 1, "%s%s%s", scheme, bld->nn, suffix);
- *uri = u;
- return 0;
-}
-
-static const char *maybeNull(const char *str)
-{
- return str ? str : "(NULL)";
-}
-
-static const char *hdfsBuilderToStr(const struct hdfsBuilder *bld,
- char *buf, size_t bufLen)
-{
- snprintf(buf, bufLen, "forceNewInstance=%d, nn=%s, port=%d, "
- "kerbTicketCachePath=%s, userName=%s",
- bld->forceNewInstance, maybeNull(bld->nn), bld->port,
- maybeNull(bld->kerbTicketCachePath), maybeNull(bld->userName));
- return buf;
-}
-
-hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld)
-{
- JNIEnv *env = 0;
- jobject jConfiguration = NULL, jFS = NULL, jURI = NULL, jCachePath = NULL;
- jstring jURIString = NULL, jUserString = NULL;
- jvalue jVal;
- jthrowable jthr = NULL;
- char *cURI = 0, buf[512];
- int ret;
- jobject jRet = NULL;
- struct hdfsBuilderConfOpt *opt;
-
- //Get the JNIEnv* corresponding to current thread
- env = getJNIEnv();
- if (env == NULL) {
- ret = EINTERNAL;
- goto done;
- }
-
- // jConfiguration = new Configuration();
- jthr = constructNewObjectOfClass(env, &jConfiguration, HADOOP_CONF, "()V");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)", hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- // set configuration values
- for (opt = bld->opts; opt; opt = opt->next) {
- jthr = hadoopConfSetStr(env, jConfiguration, opt->key, opt->val);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s): error setting conf '%s' to '%s'",
- hdfsBuilderToStr(bld, buf, sizeof(buf)), opt->key, opt->val);
- goto done;
- }
- }
-
- //Check what type of FileSystem the caller wants...
- if (bld->nn == NULL) {
- // Get a local filesystem.
- if (bld->forceNewInstance) {
- // fs = FileSytem#newInstanceLocal(conf);
- jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS,
- "newInstanceLocal", JMETHOD1(JPARAM(HADOOP_CONF),
- JPARAM(HADOOP_LOCALFS)), jConfiguration);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jFS = jVal.l;
- } else {
- // fs = FileSytem#getLocal(conf);
- jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS, "getLocal",
- JMETHOD1(JPARAM(HADOOP_CONF),
- JPARAM(HADOOP_LOCALFS)),
- jConfiguration);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jFS = jVal.l;
- }
- } else {
- if (!strcmp(bld->nn, "default")) {
- // jURI = FileSystem.getDefaultUri(conf)
- jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS,
- "getDefaultUri",
- "(Lorg/apache/hadoop/conf/Configuration;)Ljava/net/URI;",
- jConfiguration);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jURI = jVal.l;
- } else {
- // fs = FileSystem#get(URI, conf, ugi);
- ret = calcEffectiveURI(bld, &cURI);
- if (ret)
- goto done;
- jthr = newJavaStr(env, cURI, &jURIString);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jthr = invokeMethod(env, &jVal, STATIC, NULL, JAVA_NET_URI,
- "create", "(Ljava/lang/String;)Ljava/net/URI;",
- jURIString);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jURI = jVal.l;
- }
-
- if (bld->kerbTicketCachePath) {
- jthr = hadoopConfSetStr(env, jConfiguration,
- KERBEROS_TICKET_CACHE_PATH, bld->kerbTicketCachePath);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- }
- jthr = newJavaStr(env, bld->userName, &jUserString);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- if (bld->forceNewInstance) {
- jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS,
- "newInstance", JMETHOD3(JPARAM(JAVA_NET_URI),
- JPARAM(HADOOP_CONF), JPARAM(JAVA_STRING),
- JPARAM(HADOOP_FS)),
- jURI, jConfiguration, jUserString);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jFS = jVal.l;
- } else {
- jthr = invokeMethod(env, &jVal, STATIC, NULL, HADOOP_FS, "get",
- JMETHOD3(JPARAM(JAVA_NET_URI), JPARAM(HADOOP_CONF),
- JPARAM(JAVA_STRING), JPARAM(HADOOP_FS)),
- jURI, jConfiguration, jUserString);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- jFS = jVal.l;
- }
- }
- jRet = (*env)->NewGlobalRef(env, jFS);
- if (!jRet) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsBuilderConnect(%s)",
- hdfsBuilderToStr(bld, buf, sizeof(buf)));
- goto done;
- }
- ret = 0;
-
-done:
- // Release unnecessary local references
- destroyLocalReference(env, jConfiguration);
- destroyLocalReference(env, jFS);
- destroyLocalReference(env, jURI);
- destroyLocalReference(env, jCachePath);
- destroyLocalReference(env, jURIString);
- destroyLocalReference(env, jUserString);
- free(cURI);
- hdfsFreeBuilder(bld);
-
- if (ret) {
- errno = ret;
- return NULL;
- }
- return (hdfsFS)jRet;
-}
-
-int hdfsDisconnect(hdfsFS fs)
-{
- // JAVA EQUIVALENT:
- // fs.close()
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- int ret;
- jobject jFS;
- jthrowable jthr;
-
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Parameters
- jFS = (jobject)fs;
-
- //Sanity check
- if (fs == NULL) {
- errno = EBADF;
- return -1;
- }
-
- jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
- "close", "()V");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsDisconnect: FileSystem#close");
- } else {
- ret = 0;
- }
- (*env)->DeleteGlobalRef(env, jFS);
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-/**
- * Get the default block size of a FileSystem object.
- *
- * @param env The Java env
- * @param jFS The FileSystem object
- * @param jPath The path to find the default blocksize at
- * @param out (out param) the default block size
- *
- * @return NULL on success; or the exception
- */
-static jthrowable getDefaultBlockSize(JNIEnv *env, jobject jFS,
- jobject jPath, jlong *out)
-{
- jthrowable jthr;
- jvalue jVal;
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "getDefaultBlockSize", JMETHOD1(JPARAM(HADOOP_PATH), "J"), jPath);
- if (jthr)
- return jthr;
- *out = jVal.j;
- return NULL;
-}
-
-hdfsFile hdfsOpenFile(hdfsFS fs, const char *path, int flags,
- int bufferSize, short replication, tSize blockSize)
-{
- /*
- JAVA EQUIVALENT:
- File f = new File(path);
- FSData{Input|Output}Stream f{is|os} = fs.create(f);
- return f{is|os};
- */
- int accmode = flags & O_ACCMODE;
- jstring jStrBufferSize = NULL, jStrReplication = NULL;
- jobject jConfiguration = NULL, jPath = NULL, jFile = NULL;
- jobject jFS = (jobject)fs;
- jthrowable jthr;
- jvalue jVal;
- hdfsFile file = NULL;
- int ret;
- jint jBufferSize = bufferSize;
- jshort jReplication = replication;
-
- /* The hadoop java api/signature */
- const char *method = NULL;
- const char *signature = NULL;
-
- /* Get the JNIEnv* corresponding to current thread */
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return NULL;
- }
-
-
- if (accmode == O_RDONLY || accmode == O_WRONLY) {
- /* yay */
- } else if (accmode == O_RDWR) {
- fprintf(stderr, "ERROR: cannot open an hdfs file in O_RDWR mode\n");
- errno = ENOTSUP;
- return NULL;
- } else {
- fprintf(stderr, "ERROR: cannot open an hdfs file in mode 0x%x\n", accmode);
- errno = EINVAL;
- return NULL;
- }
-
- if ((flags & O_CREAT) && (flags & O_EXCL)) {
- fprintf(stderr, "WARN: hdfs does not truly support O_CREATE && O_EXCL\n");
- }
-
- if (accmode == O_RDONLY) {
- method = "open";
- signature = JMETHOD2(JPARAM(HADOOP_PATH), "I", JPARAM(HADOOP_ISTRM));
- } else if (flags & O_APPEND) {
- method = "append";
- signature = JMETHOD1(JPARAM(HADOOP_PATH), JPARAM(HADOOP_OSTRM));
- } else {
- method = "create";
- signature = JMETHOD2(JPARAM(HADOOP_PATH), "ZISJ", JPARAM(HADOOP_OSTRM));
- }
-
- /* Create an object of org.apache.hadoop.fs.Path */
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsOpenFile(%s): constructNewObjectOfPath", path);
- goto done;
- }
-
- /* Get the Configuration object from the FileSystem object */
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "getConf", JMETHOD1("", JPARAM(HADOOP_CONF)));
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsOpenFile(%s): FileSystem#getConf", path);
- goto done;
- }
- jConfiguration = jVal.l;
-
- jStrBufferSize = (*env)->NewStringUTF(env, "io.file.buffer.size");
- if (!jStrBufferSize) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL, "OOM");
- goto done;
- }
- jStrReplication = (*env)->NewStringUTF(env, "dfs.replication");
- if (!jStrReplication) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL, "OOM");
- goto done;
- }
-
- if (!bufferSize) {
- jthr = invokeMethod(env, &jVal, INSTANCE, jConfiguration,
- HADOOP_CONF, "getInt", "(Ljava/lang/String;I)I",
- jStrBufferSize, 4096);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, NOPRINT_EXC_FILE_NOT_FOUND |
- NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_UNRESOLVED_LINK,
- "hdfsOpenFile(%s): Configuration#getInt(io.file.buffer.size)",
- path);
- goto done;
- }
- jBufferSize = jVal.i;
- }
-
- if ((accmode == O_WRONLY) && (flags & O_APPEND) == 0) {
- if (!replication) {
- jthr = invokeMethod(env, &jVal, INSTANCE, jConfiguration,
- HADOOP_CONF, "getInt", "(Ljava/lang/String;I)I",
- jStrReplication, 1);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsOpenFile(%s): Configuration#getInt(dfs.replication)",
- path);
- goto done;
- }
- jReplication = (jshort)jVal.i;
- }
- }
-
- /* Create and return either the FSDataInputStream or
- FSDataOutputStream references jobject jStream */
-
- // READ?
- if (accmode == O_RDONLY) {
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- method, signature, jPath, jBufferSize);
- } else if ((accmode == O_WRONLY) && (flags & O_APPEND)) {
- // WRITE/APPEND?
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- method, signature, jPath);
- } else {
- // WRITE/CREATE
- jboolean jOverWrite = 1;
- jlong jBlockSize = blockSize;
-
- if (jBlockSize == 0) {
- jthr = getDefaultBlockSize(env, jFS, jPath, &jBlockSize);
- if (jthr) {
- ret = EIO;
- goto done;
- }
- }
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- method, signature, jPath, jOverWrite,
- jBufferSize, jReplication, jBlockSize);
- }
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsOpenFile(%s): FileSystem#%s(%s)", path, method, signature);
- goto done;
- }
- jFile = jVal.l;
-
- file = calloc(1, sizeof(struct hdfsFile_internal));
- if (!file) {
- fprintf(stderr, "hdfsOpenFile(%s): OOM create hdfsFile\n", path);
- ret = ENOMEM;
- goto done;
- }
- file->file = (*env)->NewGlobalRef(env, jFile);
- if (!file->file) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsOpenFile(%s): NewGlobalRef", path);
- goto done;
- }
- file->type = (((flags & O_WRONLY) == 0) ? HDFS_STREAM_INPUT :
- HDFS_STREAM_OUTPUT);
- file->flags = 0;
-
- if ((flags & O_WRONLY) == 0) {
- // Try a test read to see if we can do direct reads
- char buf;
- if (readDirect(fs, file, &buf, 0) == 0) {
- // Success - 0-byte read should return 0
- file->flags |= HDFS_FILE_SUPPORTS_DIRECT_READ;
- } else if (errno != ENOTSUP) {
- // Unexpected error. Clear it, don't set the direct flag.
- fprintf(stderr,
- "hdfsOpenFile(%s): WARN: Unexpected error %d when testing "
- "for direct read compatibility\n", path, errno);
- }
- }
- ret = 0;
-
-done:
- destroyLocalReference(env, jStrBufferSize);
- destroyLocalReference(env, jStrReplication);
- destroyLocalReference(env, jConfiguration);
- destroyLocalReference(env, jPath);
- destroyLocalReference(env, jFile);
- if (ret) {
- if (file) {
- if (file->file) {
- (*env)->DeleteGlobalRef(env, file->file);
- }
- free(file);
- }
- errno = ret;
- return NULL;
- }
- return file;
-}
-
-int hdfsTruncateFile(hdfsFS fs, const char* path, tOffset newlength)
-{
- jobject jFS = (jobject)fs;
- jthrowable jthr;
- jvalue jVal;
- jobject jPath = NULL;
-
- JNIEnv *env = getJNIEnv();
-
- if (!env) {
- errno = EINTERNAL;
- return -1;
- }
-
- /* Create an object of org.apache.hadoop.fs.Path */
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsTruncateFile(%s): constructNewObjectOfPath", path);
- return -1;
- }
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "truncate", JMETHOD2(JPARAM(HADOOP_PATH), "J", "Z"),
- jPath, newlength);
- destroyLocalReference(env, jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsTruncateFile(%s): FileSystem#truncate", path);
- return -1;
- }
- if (jVal.z == JNI_TRUE) {
- return 1;
- }
- return 0;
-}
-
-int hdfsUnbufferFile(hdfsFile file)
-{
- int ret;
- jthrowable jthr;
- JNIEnv *env = getJNIEnv();
-
- if (!env) {
- ret = EINTERNAL;
- goto done;
- }
- if (file->type != HDFS_STREAM_INPUT) {
- ret = ENOTSUP;
- goto done;
- }
- jthr = invokeMethod(env, NULL, INSTANCE, file->file, HADOOP_ISTRM,
- "unbuffer", "()V");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- HADOOP_ISTRM "#unbuffer failed:");
- goto done;
- }
- ret = 0;
-
-done:
- errno = ret;
- return ret;
-}
-
-int hdfsCloseFile(hdfsFS fs, hdfsFile file)
-{
- int ret;
- // JAVA EQUIVALENT:
- // file.close
-
- //The interface whose 'close' method to be called
- const char *interface;
- const char *interfaceShortName;
-
- //Caught exception
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Sanity check
- if (!file || file->type == HDFS_STREAM_UNINITIALIZED) {
- errno = EBADF;
- return -1;
- }
-
- interface = (file->type == HDFS_STREAM_INPUT) ?
- HADOOP_ISTRM : HADOOP_OSTRM;
-
- jthr = invokeMethod(env, NULL, INSTANCE, file->file, interface,
- "close", "()V");
- if (jthr) {
- interfaceShortName = (file->type == HDFS_STREAM_INPUT) ?
- "FSDataInputStream" : "FSDataOutputStream";
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "%s#close", interfaceShortName);
- } else {
- ret = 0;
- }
-
- //De-allocate memory
- (*env)->DeleteGlobalRef(env, file->file);
- free(file);
-
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsExists(hdfsFS fs, const char *path)
-{
- JNIEnv *env = getJNIEnv();
- jobject jPath;
- jvalue jVal;
- jobject jFS = (jobject)fs;
- jthrowable jthr;
-
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- if (path == NULL) {
- errno = EINVAL;
- return -1;
- }
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsExists: constructNewObjectOfPath");
- return -1;
- }
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "exists", JMETHOD1(JPARAM(HADOOP_PATH), "Z"), jPath);
- destroyLocalReference(env, jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsExists: invokeMethod(%s)",
- JMETHOD1(JPARAM(HADOOP_PATH), "Z"));
- return -1;
- }
- if (jVal.z) {
- return 0;
- } else {
- errno = ENOENT;
- return -1;
- }
-}
-
-// Checks input file for readiness for reading.
-static int readPrepare(JNIEnv* env, hdfsFS fs, hdfsFile f,
- jobject* jInputStream)
-{
- *jInputStream = (jobject)(f ? f->file : NULL);
-
- //Sanity check
- if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
- errno = EBADF;
- return -1;
- }
-
- //Error checking... make sure that this file is 'readable'
- if (f->type != HDFS_STREAM_INPUT) {
- fprintf(stderr, "Cannot read from a non-InputStream object!\n");
- errno = EINVAL;
- return -1;
- }
-
- return 0;
-}
-
-tSize hdfsRead(hdfsFS fs, hdfsFile f, void* buffer, tSize length)
-{
- jobject jInputStream;
- jbyteArray jbRarray;
- jint noReadBytes = length;
- jvalue jVal;
- jthrowable jthr;
- JNIEnv* env;
-
- if (length == 0) {
- return 0;
- } else if (length < 0) {
- errno = EINVAL;
- return -1;
- }
- if (f->flags & HDFS_FILE_SUPPORTS_DIRECT_READ) {
- return readDirect(fs, f, buffer, length);
- }
-
- // JAVA EQUIVALENT:
- // byte [] bR = new byte[length];
- // fis.read(bR);
-
- //Get the JNIEnv* corresponding to current thread
- env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Parameters
- if (readPrepare(env, fs, f, &jInputStream) == -1) {
- return -1;
- }
-
- //Read the requisite bytes
- jbRarray = (*env)->NewByteArray(env, length);
- if (!jbRarray) {
- errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsRead: NewByteArray");
- return -1;
- }
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jInputStream, HADOOP_ISTRM,
- "read", "([B)I", jbRarray);
- if (jthr) {
- destroyLocalReference(env, jbRarray);
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsRead: FSDataInputStream#read");
- return -1;
- }
- if (jVal.i < 0) {
- // EOF
- destroyLocalReference(env, jbRarray);
- return 0;
- } else if (jVal.i == 0) {
- destroyLocalReference(env, jbRarray);
- errno = EINTR;
- return -1;
- }
- (*env)->GetByteArrayRegion(env, jbRarray, 0, noReadBytes, buffer);
- destroyLocalReference(env, jbRarray);
- if ((*env)->ExceptionCheck(env)) {
- errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsRead: GetByteArrayRegion");
- return -1;
- }
- return jVal.i;
-}
-
-// Reads using the read(ByteBuffer) API, which does fewer copies
-tSize readDirect(hdfsFS fs, hdfsFile f, void* buffer, tSize length)
-{
- // JAVA EQUIVALENT:
- // ByteBuffer bbuffer = ByteBuffer.allocateDirect(length) // wraps C buffer
- // fis.read(bbuffer);
-
- jobject jInputStream;
- jvalue jVal;
- jthrowable jthr;
- jobject bb;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- if (readPrepare(env, fs, f, &jInputStream) == -1) {
- return -1;
- }
-
- //Read the requisite bytes
- bb = (*env)->NewDirectByteBuffer(env, buffer, length);
- if (bb == NULL) {
- errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "readDirect: NewDirectByteBuffer");
- return -1;
- }
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jInputStream,
- HADOOP_ISTRM, "read", "(Ljava/nio/ByteBuffer;)I", bb);
- destroyLocalReference(env, bb);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "readDirect: FSDataInputStream#read");
- return -1;
- }
- return (jVal.i < 0) ? 0 : jVal.i;
-}
-
-tSize hdfsPread(hdfsFS fs, hdfsFile f, tOffset position,
- void* buffer, tSize length)
-{
- JNIEnv* env;
- jbyteArray jbRarray;
- jvalue jVal;
- jthrowable jthr;
-
- if (length == 0) {
- return 0;
- } else if (length < 0) {
- errno = EINVAL;
- return -1;
- }
- if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
- errno = EBADF;
- return -1;
- }
-
- env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Error checking... make sure that this file is 'readable'
- if (f->type != HDFS_STREAM_INPUT) {
- fprintf(stderr, "Cannot read from a non-InputStream object!\n");
- errno = EINVAL;
- return -1;
- }
-
- // JAVA EQUIVALENT:
- // byte [] bR = new byte[length];
- // fis.read(pos, bR, 0, length);
- jbRarray = (*env)->NewByteArray(env, length);
- if (!jbRarray) {
- errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsPread: NewByteArray");
- return -1;
- }
- jthr = invokeMethod(env, &jVal, INSTANCE, f->file, HADOOP_ISTRM,
- "read", "(J[BII)I", position, jbRarray, 0, length);
- if (jthr) {
- destroyLocalReference(env, jbRarray);
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsPread: FSDataInputStream#read");
- return -1;
- }
- if (jVal.i < 0) {
- // EOF
- destroyLocalReference(env, jbRarray);
- return 0;
- } else if (jVal.i == 0) {
- destroyLocalReference(env, jbRarray);
- errno = EINTR;
- return -1;
- }
- (*env)->GetByteArrayRegion(env, jbRarray, 0, jVal.i, buffer);
- destroyLocalReference(env, jbRarray);
- if ((*env)->ExceptionCheck(env)) {
- errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsPread: GetByteArrayRegion");
- return -1;
- }
- return jVal.i;
-}
-
-tSize hdfsWrite(hdfsFS fs, hdfsFile f, const void* buffer, tSize length)
-{
- // JAVA EQUIVALENT
- // byte b[] = str.getBytes();
- // fso.write(b);
-
- jobject jOutputStream;
- jbyteArray jbWarray;
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Sanity check
- if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
- errno = EBADF;
- return -1;
- }
-
- jOutputStream = f->file;
-
- if (length < 0) {
- errno = EINVAL;
- return -1;
- }
-
- //Error checking... make sure that this file is 'writable'
- if (f->type != HDFS_STREAM_OUTPUT) {
- fprintf(stderr, "Cannot write into a non-OutputStream object!\n");
- errno = EINVAL;
- return -1;
- }
-
- if (length < 0) {
- errno = EINVAL;
- return -1;
- }
- if (length == 0) {
- return 0;
- }
- //Write the requisite bytes into the file
- jbWarray = (*env)->NewByteArray(env, length);
- if (!jbWarray) {
- errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsWrite: NewByteArray");
- return -1;
- }
- (*env)->SetByteArrayRegion(env, jbWarray, 0, length, buffer);
- if ((*env)->ExceptionCheck(env)) {
- destroyLocalReference(env, jbWarray);
- errno = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsWrite(length = %d): SetByteArrayRegion", length);
- return -1;
- }
- jthr = invokeMethod(env, NULL, INSTANCE, jOutputStream,
- HADOOP_OSTRM, "write", "([B)V", jbWarray);
- destroyLocalReference(env, jbWarray);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsWrite: FSDataOutputStream#write");
- return -1;
- }
- // Unlike most Java streams, FSDataOutputStream never does partial writes.
- // If we succeeded, all the data was written.
- return length;
-}
-
-int hdfsSeek(hdfsFS fs, hdfsFile f, tOffset desiredPos)
-{
- // JAVA EQUIVALENT
- // fis.seek(pos);
-
- jobject jInputStream;
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Sanity check
- if (!f || f->type != HDFS_STREAM_INPUT) {
- errno = EBADF;
- return -1;
- }
-
- jInputStream = f->file;
- jthr = invokeMethod(env, NULL, INSTANCE, jInputStream,
- HADOOP_ISTRM, "seek", "(J)V", desiredPos);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsSeek(desiredPos=%" PRId64 ")"
- ": FSDataInputStream#seek", desiredPos);
- return -1;
- }
- return 0;
-}
-
-
-
-tOffset hdfsTell(hdfsFS fs, hdfsFile f)
-{
- // JAVA EQUIVALENT
- // pos = f.getPos();
-
- jobject jStream;
- const char *interface;
- jvalue jVal;
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Sanity check
- if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
- errno = EBADF;
- return -1;
- }
-
- //Parameters
- jStream = f->file;
- interface = (f->type == HDFS_STREAM_INPUT) ?
- HADOOP_ISTRM : HADOOP_OSTRM;
- jthr = invokeMethod(env, &jVal, INSTANCE, jStream,
- interface, "getPos", "()J");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsTell: %s#getPos",
- ((f->type == HDFS_STREAM_INPUT) ? "FSDataInputStream" :
- "FSDataOutputStream"));
- return -1;
- }
- return jVal.j;
-}
-
-int hdfsFlush(hdfsFS fs, hdfsFile f)
-{
- // JAVA EQUIVALENT
- // fos.flush();
-
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Sanity check
- if (!f || f->type != HDFS_STREAM_OUTPUT) {
- errno = EBADF;
- return -1;
- }
- jthr = invokeMethod(env, NULL, INSTANCE, f->file,
- HADOOP_OSTRM, "flush", "()V");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsFlush: FSDataInputStream#flush");
- return -1;
- }
- return 0;
-}
-
-int hdfsHFlush(hdfsFS fs, hdfsFile f)
-{
- jobject jOutputStream;
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Sanity check
- if (!f || f->type != HDFS_STREAM_OUTPUT) {
- errno = EBADF;
- return -1;
- }
-
- jOutputStream = f->file;
- jthr = invokeMethod(env, NULL, INSTANCE, jOutputStream,
- HADOOP_OSTRM, "hflush", "()V");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsHFlush: FSDataOutputStream#hflush");
- return -1;
- }
- return 0;
-}
-
-int hdfsHSync(hdfsFS fs, hdfsFile f)
-{
- jobject jOutputStream;
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Sanity check
- if (!f || f->type != HDFS_STREAM_OUTPUT) {
- errno = EBADF;
- return -1;
- }
-
- jOutputStream = f->file;
- jthr = invokeMethod(env, NULL, INSTANCE, jOutputStream,
- HADOOP_OSTRM, "hsync", "()V");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsHSync: FSDataOutputStream#hsync");
- return -1;
- }
- return 0;
-}
-
-int hdfsAvailable(hdfsFS fs, hdfsFile f)
-{
- // JAVA EQUIVALENT
- // fis.available();
-
- jobject jInputStream;
- jvalue jVal;
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Sanity check
- if (!f || f->type != HDFS_STREAM_INPUT) {
- errno = EBADF;
- return -1;
- }
-
- //Parameters
- jInputStream = f->file;
- jthr = invokeMethod(env, &jVal, INSTANCE, jInputStream,
- HADOOP_ISTRM, "available", "()I");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsAvailable: FSDataInputStream#available");
- return -1;
- }
- return jVal.i;
-}
-
-static int hdfsCopyImpl(hdfsFS srcFS, const char *src, hdfsFS dstFS,
- const char *dst, jboolean deleteSource)
-{
- //JAVA EQUIVALENT
- // FileUtil#copy(srcFS, srcPath, dstFS, dstPath,
- // deleteSource = false, conf)
-
- //Parameters
- jobject jSrcFS = (jobject)srcFS;
- jobject jDstFS = (jobject)dstFS;
- jobject jConfiguration = NULL, jSrcPath = NULL, jDstPath = NULL;
- jthrowable jthr;
- jvalue jVal;
- int ret;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- jthr = constructNewObjectOfPath(env, src, &jSrcPath);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsCopyImpl(src=%s): constructNewObjectOfPath", src);
- goto done;
- }
- jthr = constructNewObjectOfPath(env, dst, &jDstPath);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsCopyImpl(dst=%s): constructNewObjectOfPath", dst);
- goto done;
- }
-
- //Create the org.apache.hadoop.conf.Configuration object
- jthr = constructNewObjectOfClass(env, &jConfiguration,
- HADOOP_CONF, "()V");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsCopyImpl: Configuration constructor");
- goto done;
- }
-
- //FileUtil#copy
- jthr = invokeMethod(env, &jVal, STATIC,
- NULL, "org/apache/hadoop/fs/FileUtil", "copy",
- "(Lorg/apache/hadoop/fs/FileSystem;Lorg/apache/hadoop/fs/Path;"
- "Lorg/apache/hadoop/fs/FileSystem;Lorg/apache/hadoop/fs/Path;"
- "ZLorg/apache/hadoop/conf/Configuration;)Z",
- jSrcFS, jSrcPath, jDstFS, jDstPath, deleteSource,
- jConfiguration);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsCopyImpl(src=%s, dst=%s, deleteSource=%d): "
- "FileUtil#copy", src, dst, deleteSource);
- goto done;
- }
- if (!jVal.z) {
- ret = EIO;
- goto done;
- }
- ret = 0;
-
-done:
- destroyLocalReference(env, jConfiguration);
- destroyLocalReference(env, jSrcPath);
- destroyLocalReference(env, jDstPath);
-
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsCopy(hdfsFS srcFS, const char *src, hdfsFS dstFS, const char *dst)
-{
- return hdfsCopyImpl(srcFS, src, dstFS, dst, 0);
-}
-
-int hdfsMove(hdfsFS srcFS, const char *src, hdfsFS dstFS, const char *dst)
-{
- return hdfsCopyImpl(srcFS, src, dstFS, dst, 1);
-}
-
-int hdfsDelete(hdfsFS fs, const char *path, int recursive)
-{
- // JAVA EQUIVALENT:
- // Path p = new Path(path);
- // bool retval = fs.delete(p, recursive);
-
- jobject jFS = (jobject)fs;
- jthrowable jthr;
- jobject jPath;
- jvalue jVal;
- jboolean jRecursive;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsDelete(path=%s): constructNewObjectOfPath", path);
- return -1;
- }
- jRecursive = recursive ? JNI_TRUE : JNI_FALSE;
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "delete", "(Lorg/apache/hadoop/fs/Path;Z)Z",
- jPath, jRecursive);
- destroyLocalReference(env, jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsDelete(path=%s, recursive=%d): "
- "FileSystem#delete", path, recursive);
- return -1;
- }
- if (!jVal.z) {
- errno = EIO;
- return -1;
- }
- return 0;
-}
-
-
-
-int hdfsRename(hdfsFS fs, const char *oldPath, const char *newPath)
-{
- // JAVA EQUIVALENT:
- // Path old = new Path(oldPath);
- // Path new = new Path(newPath);
- // fs.rename(old, new);
-
- jobject jFS = (jobject)fs;
- jthrowable jthr;
- jobject jOldPath = NULL, jNewPath = NULL;
- int ret = -1;
- jvalue jVal;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- jthr = constructNewObjectOfPath(env, oldPath, &jOldPath );
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsRename: constructNewObjectOfPath(%s)", oldPath);
- goto done;
- }
- jthr = constructNewObjectOfPath(env, newPath, &jNewPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsRename: constructNewObjectOfPath(%s)", newPath);
- goto done;
- }
-
- // Rename the file
- // TODO: use rename2 here? (See HDFS-3592)
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS, "rename",
- JMETHOD2(JPARAM(HADOOP_PATH), JPARAM(HADOOP_PATH), "Z"),
- jOldPath, jNewPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsRename(oldPath=%s, newPath=%s): FileSystem#rename",
- oldPath, newPath);
- goto done;
- }
- if (!jVal.z) {
- errno = EIO;
- goto done;
- }
- ret = 0;
-
-done:
- destroyLocalReference(env, jOldPath);
- destroyLocalReference(env, jNewPath);
- return ret;
-}
-
-
-
-char* hdfsGetWorkingDirectory(hdfsFS fs, char* buffer, size_t bufferSize)
-{
- // JAVA EQUIVALENT:
- // Path p = fs.getWorkingDirectory();
- // return p.toString()
-
- jobject jPath = NULL;
- jstring jPathString = NULL;
- jobject jFS = (jobject)fs;
- jvalue jVal;
- jthrowable jthr;
- int ret;
- const char *jPathChars = NULL;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return NULL;
- }
-
- //FileSystem#getWorkingDirectory()
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS,
- HADOOP_FS, "getWorkingDirectory",
- "()Lorg/apache/hadoop/fs/Path;");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetWorkingDirectory: FileSystem#getWorkingDirectory");
- goto done;
- }
- jPath = jVal.l;
- if (!jPath) {
- fprintf(stderr, "hdfsGetWorkingDirectory: "
- "FileSystem#getWorkingDirectory returned NULL");
- ret = -EIO;
- goto done;
- }
-
- //Path#toString()
- jthr = invokeMethod(env, &jVal, INSTANCE, jPath,
- "org/apache/hadoop/fs/Path", "toString",
- "()Ljava/lang/String;");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetWorkingDirectory: Path#toString");
- goto done;
- }
- jPathString = jVal.l;
- jPathChars = (*env)->GetStringUTFChars(env, jPathString, NULL);
- if (!jPathChars) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsGetWorkingDirectory: GetStringUTFChars");
- goto done;
- }
-
- //Copy to user-provided buffer
- ret = snprintf(buffer, bufferSize, "%s", jPathChars);
- if (ret >= bufferSize) {
- ret = ENAMETOOLONG;
- goto done;
- }
- ret = 0;
-
-done:
- if (jPathChars) {
- (*env)->ReleaseStringUTFChars(env, jPathString, jPathChars);
- }
- destroyLocalReference(env, jPath);
- destroyLocalReference(env, jPathString);
-
- if (ret) {
- errno = ret;
- return NULL;
- }
- return buffer;
-}
-
-
-
-int hdfsSetWorkingDirectory(hdfsFS fs, const char *path)
-{
- // JAVA EQUIVALENT:
- // fs.setWorkingDirectory(Path(path));
-
- jobject jFS = (jobject)fs;
- jthrowable jthr;
- jobject jPath;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Create an object of org.apache.hadoop.fs.Path
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsSetWorkingDirectory(%s): constructNewObjectOfPath",
- path);
- return -1;
- }
-
- //FileSystem#setWorkingDirectory()
- jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
- "setWorkingDirectory",
- "(Lorg/apache/hadoop/fs/Path;)V", jPath);
- destroyLocalReference(env, jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, NOPRINT_EXC_ILLEGAL_ARGUMENT,
- "hdfsSetWorkingDirectory(%s): FileSystem#setWorkingDirectory",
- path);
- return -1;
- }
- return 0;
-}
-
-
-
-int hdfsCreateDirectory(hdfsFS fs, const char *path)
-{
- // JAVA EQUIVALENT:
- // fs.mkdirs(new Path(path));
-
- jobject jFS = (jobject)fs;
- jobject jPath;
- jthrowable jthr;
- jvalue jVal;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Create an object of org.apache.hadoop.fs.Path
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsCreateDirectory(%s): constructNewObjectOfPath", path);
- return -1;
- }
-
- //Create the directory
- jVal.z = 0;
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "mkdirs", "(Lorg/apache/hadoop/fs/Path;)Z",
- jPath);
- destroyLocalReference(env, jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr,
- NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_FILE_NOT_FOUND |
- NOPRINT_EXC_UNRESOLVED_LINK | NOPRINT_EXC_PARENT_NOT_DIRECTORY,
- "hdfsCreateDirectory(%s): FileSystem#mkdirs", path);
- return -1;
- }
- if (!jVal.z) {
- // It's unclear under exactly which conditions FileSystem#mkdirs
- // is supposed to return false (as opposed to throwing an exception.)
- // It seems like the current code never actually returns false.
- // So we're going to translate this to EIO, since there seems to be
- // nothing more specific we can do with it.
- errno = EIO;
- return -1;
- }
- return 0;
-}
-
-
-int hdfsSetReplication(hdfsFS fs, const char *path, int16_t replication)
-{
- // JAVA EQUIVALENT:
- // fs.setReplication(new Path(path), replication);
-
- jobject jFS = (jobject)fs;
- jthrowable jthr;
- jobject jPath;
- jvalue jVal;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Create an object of org.apache.hadoop.fs.Path
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsSetReplication(path=%s): constructNewObjectOfPath", path);
- return -1;
- }
-
- //Create the directory
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "setReplication", "(Lorg/apache/hadoop/fs/Path;S)Z",
- jPath, replication);
- destroyLocalReference(env, jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsSetReplication(path=%s, replication=%d): "
- "FileSystem#setReplication", path, replication);
- return -1;
- }
- if (!jVal.z) {
- // setReplication returns false "if file does not exist or is a
- // directory." So the nearest translation to that is ENOENT.
- errno = ENOENT;
- return -1;
- }
-
- return 0;
-}
-
-int hdfsChown(hdfsFS fs, const char *path, const char *owner, const char *group)
-{
- // JAVA EQUIVALENT:
- // fs.setOwner(path, owner, group)
-
- jobject jFS = (jobject)fs;
- jobject jPath = NULL;
- jstring jOwner = NULL, jGroup = NULL;
- jthrowable jthr;
- int ret;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- if (owner == NULL && group == NULL) {
- return 0;
- }
-
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsChown(path=%s): constructNewObjectOfPath", path);
- goto done;
- }
-
- jthr = newJavaStr(env, owner, &jOwner);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsChown(path=%s): newJavaStr(%s)", path, owner);
- goto done;
- }
- jthr = newJavaStr(env, group, &jGroup);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsChown(path=%s): newJavaStr(%s)", path, group);
- goto done;
- }
-
- //Create the directory
- jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
- "setOwner", JMETHOD3(JPARAM(HADOOP_PATH),
- JPARAM(JAVA_STRING), JPARAM(JAVA_STRING), JAVA_VOID),
- jPath, jOwner, jGroup);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr,
- NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_FILE_NOT_FOUND |
- NOPRINT_EXC_UNRESOLVED_LINK,
- "hdfsChown(path=%s, owner=%s, group=%s): "
- "FileSystem#setOwner", path, owner, group);
- goto done;
- }
- ret = 0;
-
-done:
- destroyLocalReference(env, jPath);
- destroyLocalReference(env, jOwner);
- destroyLocalReference(env, jGroup);
-
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsChmod(hdfsFS fs, const char *path, short mode)
-{
- int ret;
- // JAVA EQUIVALENT:
- // fs.setPermission(path, FsPermission)
-
- jthrowable jthr;
- jobject jPath = NULL, jPermObj = NULL;
- jobject jFS = (jobject)fs;
- jshort jmode = mode;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- // construct jPerm = FsPermission.createImmutable(short mode);
- jthr = constructNewObjectOfClass(env, &jPermObj,
- HADOOP_FSPERM,"(S)V",jmode);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "constructNewObjectOfClass(%s)", HADOOP_FSPERM);
- return -1;
- }
-
- //Create an object of org.apache.hadoop.fs.Path
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsChmod(%s): constructNewObjectOfPath", path);
- goto done;
- }
-
- //Create the directory
- jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
- "setPermission",
- JMETHOD2(JPARAM(HADOOP_PATH), JPARAM(HADOOP_FSPERM), JAVA_VOID),
- jPath, jPermObj);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr,
- NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_FILE_NOT_FOUND |
- NOPRINT_EXC_UNRESOLVED_LINK,
- "hdfsChmod(%s): FileSystem#setPermission", path);
- goto done;
- }
- ret = 0;
-
-done:
- destroyLocalReference(env, jPath);
- destroyLocalReference(env, jPermObj);
-
- if (ret) {
- errno = ret;
- return -1;
- }
- return 0;
-}
-
-int hdfsUtime(hdfsFS fs, const char *path, tTime mtime, tTime atime)
-{
- // JAVA EQUIVALENT:
- // fs.setTimes(src, mtime, atime)
-
- jthrowable jthr;
- jobject jFS = (jobject)fs;
- jobject jPath;
- static const tTime NO_CHANGE = -1;
- jlong jmtime, jatime;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //Create an object of org.apache.hadoop.fs.Path
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsUtime(path=%s): constructNewObjectOfPath", path);
- return -1;
- }
-
- jmtime = (mtime == NO_CHANGE) ? -1 : (mtime * (jlong)1000);
- jatime = (atime == NO_CHANGE) ? -1 : (atime * (jlong)1000);
-
- jthr = invokeMethod(env, NULL, INSTANCE, jFS, HADOOP_FS,
- "setTimes", JMETHOD3(JPARAM(HADOOP_PATH), "J", "J", JAVA_VOID),
- jPath, jmtime, jatime);
- destroyLocalReference(env, jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr,
- NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_FILE_NOT_FOUND |
- NOPRINT_EXC_UNRESOLVED_LINK,
- "hdfsUtime(path=%s): FileSystem#setTimes", path);
- return -1;
- }
- return 0;
-}
-
-/**
- * Zero-copy options.
- *
- * We cache the EnumSet of ReadOptions which has to be passed into every
- * readZero call, to avoid reconstructing it each time. This cache is cleared
- * whenever an element changes.
- */
-struct hadoopRzOptions
-{
- JNIEnv *env;
- int skipChecksums;
- jobject byteBufferPool;
- jobject cachedEnumSet;
-};
-
-struct hadoopRzOptions *hadoopRzOptionsAlloc(void)
-{
- struct hadoopRzOptions *opts;
- JNIEnv *env;
-
- env = getJNIEnv();
- if (!env) {
- // Check to make sure the JNI environment is set up properly.
- errno = EINTERNAL;
- return NULL;
- }
- opts = calloc(1, sizeof(struct hadoopRzOptions));
- if (!opts) {
- errno = ENOMEM;
- return NULL;
- }
- return opts;
-}
-
-static void hadoopRzOptionsClearCached(JNIEnv *env,
- struct hadoopRzOptions *opts)
-{
- if (!opts->cachedEnumSet) {
- return;
- }
- (*env)->DeleteGlobalRef(env, opts->cachedEnumSet);
- opts->cachedEnumSet = NULL;
-}
-
-int hadoopRzOptionsSetSkipChecksum(
- struct hadoopRzOptions *opts, int skip)
-{
- JNIEnv *env;
- env = getJNIEnv();
- if (!env) {
- errno = EINTERNAL;
- return -1;
- }
- hadoopRzOptionsClearCached(env, opts);
- opts->skipChecksums = !!skip;
- return 0;
-}
-
-int hadoopRzOptionsSetByteBufferPool(
- struct hadoopRzOptions *opts, const char *className)
-{
- JNIEnv *env;
- jthrowable jthr;
- jobject byteBufferPool = NULL;
-
- env = getJNIEnv();
- if (!env) {
- errno = EINTERNAL;
- return -1;
- }
-
- if (className) {
- // Note: we don't have to call hadoopRzOptionsClearCached in this
- // function, since the ByteBufferPool is passed separately from the
- // EnumSet of ReadOptions.
-
- jthr = constructNewObjectOfClass(env, &byteBufferPool, className, "()V");
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hadoopRzOptionsSetByteBufferPool(className=%s): ", className);
- errno = EINVAL;
- return -1;
- }
- }
- if (opts->byteBufferPool) {
- // Delete any previous ByteBufferPool we had.
- (*env)->DeleteGlobalRef(env, opts->byteBufferPool);
- }
- opts->byteBufferPool = byteBufferPool;
- return 0;
-}
-
-void hadoopRzOptionsFree(struct hadoopRzOptions *opts)
-{
- JNIEnv *env;
- env = getJNIEnv();
- if (!env) {
- return;
- }
- hadoopRzOptionsClearCached(env, opts);
- if (opts->byteBufferPool) {
- (*env)->DeleteGlobalRef(env, opts->byteBufferPool);
- opts->byteBufferPool = NULL;
- }
- free(opts);
-}
-
-struct hadoopRzBuffer
-{
- jobject byteBuffer;
- uint8_t *ptr;
- int32_t length;
- int direct;
-};
-
-static jthrowable hadoopRzOptionsGetEnumSet(JNIEnv *env,
- struct hadoopRzOptions *opts, jobject *enumSet)
-{
- jthrowable jthr = NULL;
- jobject enumInst = NULL, enumSetObj = NULL;
- jvalue jVal;
-
- if (opts->cachedEnumSet) {
- // If we cached the value, return it now.
- *enumSet = opts->cachedEnumSet;
- goto done;
- }
- if (opts->skipChecksums) {
- jthr = fetchEnumInstance(env, READ_OPTION,
- "SKIP_CHECKSUMS", &enumInst);
- if (jthr) {
- goto done;
- }
- jthr = invokeMethod(env, &jVal, STATIC, NULL,
- "java/util/EnumSet", "of",
- "(Ljava/lang/Enum;)Ljava/util/EnumSet;", enumInst);
- if (jthr) {
- goto done;
- }
- enumSetObj = jVal.l;
- } else {
- jclass clazz = (*env)->FindClass(env, READ_OPTION);
- if (!clazz) {
- jthr = newRuntimeError(env, "failed "
- "to find class for %s", READ_OPTION);
- goto done;
- }
- jthr = invokeMethod(env, &jVal, STATIC, NULL,
- "java/util/EnumSet", "noneOf",
- "(Ljava/lang/Class;)Ljava/util/EnumSet;", clazz);
- enumSetObj = jVal.l;
- }
- // create global ref
- opts->cachedEnumSet = (*env)->NewGlobalRef(env, enumSetObj);
- if (!opts->cachedEnumSet) {
- jthr = getPendingExceptionAndClear(env);
- goto done;
- }
- *enumSet = opts->cachedEnumSet;
- jthr = NULL;
-done:
- (*env)->DeleteLocalRef(env, enumInst);
- (*env)->DeleteLocalRef(env, enumSetObj);
- return jthr;
-}
-
-static int hadoopReadZeroExtractBuffer(JNIEnv *env,
- const struct hadoopRzOptions *opts, struct hadoopRzBuffer *buffer)
-{
- int ret;
- jthrowable jthr;
- jvalue jVal;
- uint8_t *directStart;
- void *mallocBuf = NULL;
- jint position;
- jarray array = NULL;
-
- jthr = invokeMethod(env, &jVal, INSTANCE, buffer->byteBuffer,
- "java/nio/ByteBuffer", "remaining", "()I");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hadoopReadZeroExtractBuffer: ByteBuffer#remaining failed: ");
- goto done;
- }
- buffer->length = jVal.i;
- jthr = invokeMethod(env, &jVal, INSTANCE, buffer->byteBuffer,
- "java/nio/ByteBuffer", "position", "()I");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hadoopReadZeroExtractBuffer: ByteBuffer#position failed: ");
- goto done;
- }
- position = jVal.i;
- directStart = (*env)->GetDirectBufferAddress(env, buffer->byteBuffer);
- if (directStart) {
- // Handle direct buffers.
- buffer->ptr = directStart + position;
- buffer->direct = 1;
- ret = 0;
- goto done;
- }
- // Handle indirect buffers.
- // The JNI docs don't say that GetDirectBufferAddress throws any exceptions
- // when it fails. However, they also don't clearly say that it doesn't. It
- // seems safest to clear any pending exceptions here, to prevent problems on
- // various JVMs.
- (*env)->ExceptionClear(env);
- if (!opts->byteBufferPool) {
- fputs("hadoopReadZeroExtractBuffer: we read through the "
- "zero-copy path, but failed to get the address of the buffer via "
- "GetDirectBufferAddress. Please make sure your JVM supports "
- "GetDirectBufferAddress.\n", stderr);
- ret = ENOTSUP;
- goto done;
- }
- // Get the backing array object of this buffer.
- jthr = invokeMethod(env, &jVal, INSTANCE, buffer->byteBuffer,
- "java/nio/ByteBuffer", "array", "()[B");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hadoopReadZeroExtractBuffer: ByteBuffer#array failed: ");
- goto done;
- }
- array = jVal.l;
- if (!array) {
- fputs("hadoopReadZeroExtractBuffer: ByteBuffer#array returned NULL.",
- stderr);
- ret = EIO;
- goto done;
- }
- mallocBuf = malloc(buffer->length);
- if (!mallocBuf) {
- fprintf(stderr, "hadoopReadZeroExtractBuffer: failed to allocate %d bytes of memory\n",
- buffer->length);
- ret = ENOMEM;
- goto done;
- }
- (*env)->GetByteArrayRegion(env, array, position, buffer->length, mallocBuf);
- jthr = (*env)->ExceptionOccurred(env);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hadoopReadZeroExtractBuffer: GetByteArrayRegion failed: ");
- goto done;
- }
- buffer->ptr = mallocBuf;
- buffer->direct = 0;
- ret = 0;
-
-done:
- free(mallocBuf);
- (*env)->DeleteLocalRef(env, array);
- return ret;
-}
-
-static int translateZCRException(JNIEnv *env, jthrowable exc)
-{
- int ret;
- char *className = NULL;
- jthrowable jthr = classNameOfObject(exc, env, &className);
-
- if (jthr) {
- fputs("hadoopReadZero: failed to get class name of "
- "exception from read().\n", stderr);
- destroyLocalReference(env, exc);
- destroyLocalReference(env, jthr);
- ret = EIO;
- goto done;
- }
- if (!strcmp(className, "java.lang.UnsupportedOperationException")) {
- ret = EPROTONOSUPPORT;
- goto done;
- }
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hadoopZeroCopyRead: ZeroCopyCursor#read failed");
-done:
- free(className);
- return ret;
-}
-
-struct hadoopRzBuffer* hadoopReadZero(hdfsFile file,
- struct hadoopRzOptions *opts, int32_t maxLength)
-{
- JNIEnv *env;
- jthrowable jthr = NULL;
- jvalue jVal;
- jobject enumSet = NULL, byteBuffer = NULL;
- struct hadoopRzBuffer* buffer = NULL;
- int ret;
-
- env = getJNIEnv();
- if (!env) {
- errno = EINTERNAL;
- return NULL;
- }
- if (file->type != HDFS_STREAM_INPUT) {
- fputs("Cannot read from a non-InputStream object!\n", stderr);
- ret = EINVAL;
- goto done;
- }
- buffer = calloc(1, sizeof(struct hadoopRzBuffer));
- if (!buffer) {
- ret = ENOMEM;
- goto done;
- }
- jthr = hadoopRzOptionsGetEnumSet(env, opts, &enumSet);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hadoopReadZero: hadoopRzOptionsGetEnumSet failed: ");
- goto done;
- }
- jthr = invokeMethod(env, &jVal, INSTANCE, file->file, HADOOP_ISTRM, "read",
- "(Lorg/apache/hadoop/io/ByteBufferPool;ILjava/util/EnumSet;)"
- "Ljava/nio/ByteBuffer;", opts->byteBufferPool, maxLength, enumSet);
- if (jthr) {
- ret = translateZCRException(env, jthr);
- goto done;
- }
- byteBuffer = jVal.l;
- if (!byteBuffer) {
- buffer->byteBuffer = NULL;
- buffer->length = 0;
- buffer->ptr = NULL;
- } else {
- buffer->byteBuffer = (*env)->NewGlobalRef(env, byteBuffer);
- if (!buffer->byteBuffer) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hadoopReadZero: failed to create global ref to ByteBuffer");
- goto done;
- }
- ret = hadoopReadZeroExtractBuffer(env, opts, buffer);
- if (ret) {
- goto done;
- }
- }
- ret = 0;
-done:
- (*env)->DeleteLocalRef(env, byteBuffer);
- if (ret) {
- if (buffer) {
- if (buffer->byteBuffer) {
- (*env)->DeleteGlobalRef(env, buffer->byteBuffer);
- }
- free(buffer);
- }
- errno = ret;
- return NULL;
- } else {
- errno = 0;
- }
- return buffer;
-}
-
-int32_t hadoopRzBufferLength(const struct hadoopRzBuffer *buffer)
-{
- return buffer->length;
-}
-
-const void *hadoopRzBufferGet(const struct hadoopRzBuffer *buffer)
-{
- return buffer->ptr;
-}
-
-void hadoopRzBufferFree(hdfsFile file, struct hadoopRzBuffer *buffer)
-{
- jvalue jVal;
- jthrowable jthr;
- JNIEnv* env;
-
- env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return;
- }
- if (buffer->byteBuffer) {
- jthr = invokeMethod(env, &jVal, INSTANCE, file->file,
- HADOOP_ISTRM, "releaseBuffer",
- "(Ljava/nio/ByteBuffer;)V", buffer->byteBuffer);
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hadoopRzBufferFree: releaseBuffer failed: ");
- // even on error, we have to delete the reference.
- }
- (*env)->DeleteGlobalRef(env, buffer->byteBuffer);
- }
- if (!buffer->direct) {
- free(buffer->ptr);
- }
- memset(buffer, 0, sizeof(*buffer));
- free(buffer);
-}
-
-char***
-hdfsGetHosts(hdfsFS fs, const char *path, tOffset start, tOffset length)
-{
- // JAVA EQUIVALENT:
- // fs.getFileBlockLoctions(new Path(path), start, length);
-
- jobject jFS = (jobject)fs;
- jthrowable jthr;
- jobject jPath = NULL;
- jobject jFileStatus = NULL;
- jvalue jFSVal, jVal;
- jobjectArray jBlockLocations = NULL, jFileBlockHosts = NULL;
- jstring jHost = NULL;
- char*** blockHosts = NULL;
- int i, j, ret;
- jsize jNumFileBlocks = 0;
- jobject jFileBlock;
- jsize jNumBlockHosts;
- const char *hostName;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return NULL;
- }
-
- //Create an object of org.apache.hadoop.fs.Path
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetHosts(path=%s): constructNewObjectOfPath", path);
- goto done;
- }
- jthr = invokeMethod(env, &jFSVal, INSTANCE, jFS,
- HADOOP_FS, "getFileStatus", "(Lorg/apache/hadoop/fs/Path;)"
- "Lorg/apache/hadoop/fs/FileStatus;", jPath);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, NOPRINT_EXC_FILE_NOT_FOUND,
- "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
- "FileSystem#getFileStatus", path, start, length);
- destroyLocalReference(env, jPath);
- goto done;
- }
- jFileStatus = jFSVal.l;
-
- //org.apache.hadoop.fs.FileSystem#getFileBlockLocations
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS,
- HADOOP_FS, "getFileBlockLocations",
- "(Lorg/apache/hadoop/fs/FileStatus;JJ)"
- "[Lorg/apache/hadoop/fs/BlockLocation;",
- jFileStatus, start, length);
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
- "FileSystem#getFileBlockLocations", path, start, length);
- goto done;
- }
- jBlockLocations = jVal.l;
-
- //Figure out no of entries in jBlockLocations
- //Allocate memory and add NULL at the end
- jNumFileBlocks = (*env)->GetArrayLength(env, jBlockLocations);
-
- blockHosts = calloc(jNumFileBlocks + 1, sizeof(char**));
- if (blockHosts == NULL) {
- ret = ENOMEM;
- goto done;
- }
- if (jNumFileBlocks == 0) {
- ret = 0;
- goto done;
- }
-
- //Now parse each block to get hostnames
- for (i = 0; i < jNumFileBlocks; ++i) {
- jFileBlock =
- (*env)->GetObjectArrayElement(env, jBlockLocations, i);
- if (!jFileBlock) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
- "GetObjectArrayElement(%d)", path, start, length, i);
- goto done;
- }
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jFileBlock, HADOOP_BLK_LOC,
- "getHosts", "()[Ljava/lang/String;");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
- "BlockLocation#getHosts", path, start, length);
- goto done;
- }
- jFileBlockHosts = jVal.l;
- if (!jFileBlockHosts) {
- fprintf(stderr,
- "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"):"
- "BlockLocation#getHosts returned NULL", path, start, length);
- ret = EINTERNAL;
- goto done;
- }
- //Figure out no of hosts in jFileBlockHosts, and allocate the memory
- jNumBlockHosts = (*env)->GetArrayLength(env, jFileBlockHosts);
- blockHosts[i] = calloc(jNumBlockHosts + 1, sizeof(char*));
- if (!blockHosts[i]) {
- ret = ENOMEM;
- goto done;
- }
-
- //Now parse each hostname
- for (j = 0; j < jNumBlockHosts; ++j) {
- jHost = (*env)->GetObjectArrayElement(env, jFileBlockHosts, j);
- if (!jHost) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64"): "
- "NewByteArray", path, start, length);
- goto done;
- }
- hostName =
- (const char*)((*env)->GetStringUTFChars(env, jHost, NULL));
- if (!hostName) {
- ret = printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "hdfsGetHosts(path=%s, start=%"PRId64", length=%"PRId64", "
- "j=%d out of %d): GetStringUTFChars",
- path, start, length, j, jNumBlockHosts);
- goto done;
- }
- blockHosts[i][j] = strdup(hostName);
- (*env)->ReleaseStringUTFChars(env, jHost, hostName);
- if (!blockHosts[i][j]) {
- ret = ENOMEM;
- goto done;
- }
- destroyLocalReference(env, jHost);
- jHost = NULL;
- }
-
- destroyLocalReference(env, jFileBlockHosts);
- jFileBlockHosts = NULL;
- }
- ret = 0;
-
-done:
- destroyLocalReference(env, jPath);
- destroyLocalReference(env, jFileStatus);
- destroyLocalReference(env, jBlockLocations);
- destroyLocalReference(env, jFileBlockHosts);
- destroyLocalReference(env, jHost);
- if (ret) {
- if (blockHosts) {
- hdfsFreeHosts(blockHosts);
- }
- return NULL;
- }
-
- return blockHosts;
-}
-
-
-void hdfsFreeHosts(char ***blockHosts)
-{
- int i, j;
- for (i=0; blockHosts[i]; i++) {
- for (j=0; blockHosts[i][j]; j++) {
- free(blockHosts[i][j]);
- }
- free(blockHosts[i]);
- }
- free(blockHosts);
-}
-
-
-tOffset hdfsGetDefaultBlockSize(hdfsFS fs)
-{
- // JAVA EQUIVALENT:
- // fs.getDefaultBlockSize();
-
- jobject jFS = (jobject)fs;
- jvalue jVal;
- jthrowable jthr;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //FileSystem#getDefaultBlockSize()
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "getDefaultBlockSize", "()J");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetDefaultBlockSize: FileSystem#getDefaultBlockSize");
- return -1;
- }
- return jVal.j;
-}
-
-
-tOffset hdfsGetDefaultBlockSizeAtPath(hdfsFS fs, const char *path)
-{
- // JAVA EQUIVALENT:
- // fs.getDefaultBlockSize(path);
-
- jthrowable jthr;
- jobject jFS = (jobject)fs;
- jobject jPath;
- tOffset blockSize;
- JNIEnv* env = getJNIEnv();
-
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
- jthr = constructNewObjectOfPath(env, path, &jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetDefaultBlockSize(path=%s): constructNewObjectOfPath",
- path);
- return -1;
- }
- jthr = getDefaultBlockSize(env, jFS, jPath, &blockSize);
- (*env)->DeleteLocalRef(env, jPath);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetDefaultBlockSize(path=%s): "
- "FileSystem#getDefaultBlockSize", path);
- return -1;
- }
- return blockSize;
-}
-
-
-tOffset hdfsGetCapacity(hdfsFS fs)
-{
- // JAVA EQUIVALENT:
- // FsStatus fss = fs.getStatus();
- // return Fss.getCapacity();
-
- jobject jFS = (jobject)fs;
- jvalue jVal;
- jthrowable jthr;
- jobject fss;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //FileSystem#getStatus
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "getStatus", "()Lorg/apache/hadoop/fs/FsStatus;");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetCapacity: FileSystem#getStatus");
- return -1;
- }
- fss = (jobject)jVal.l;
- jthr = invokeMethod(env, &jVal, INSTANCE, fss, HADOOP_FSSTATUS,
- "getCapacity", "()J");
- destroyLocalReference(env, fss);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetCapacity: FsStatus#getCapacity");
- return -1;
- }
- return jVal.j;
-}
-
-
-
-tOffset hdfsGetUsed(hdfsFS fs)
-{
- // JAVA EQUIVALENT:
- // FsStatus fss = fs.getStatus();
- // return Fss.getUsed();
-
- jobject jFS = (jobject)fs;
- jvalue jVal;
- jthrowable jthr;
- jobject fss;
-
- //Get the JNIEnv* corresponding to current thread
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
-
- //FileSystem#getStatus
- jthr = invokeMethod(env, &jVal, INSTANCE, jFS, HADOOP_FS,
- "getStatus", "()Lorg/apache/hadoop/fs/FsStatus;");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetUsed: FileSystem#getStatus");
- return -1;
- }
- fss = (jobject)jVal.l;
- jthr = invokeMethod(env, &jVal, INSTANCE, fss, HADOOP_FSSTATUS,
- "getUsed", "()J");
- destroyLocalReference(env, fss);
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "hdfsGetUsed: FsStatus#getUsed");
- return -1;
- }
- return jVal.j;
-}
-
-/**
- * We cannot add new fields to the hdfsFileInfo structure because it would break
- * binary compatibility. The reason is because we return an array
- * of hdfsFileInfo structures from hdfsListDirectory. So changing the size of
- * those structures would break all programs that relied on finding the second
- * element in the array at <base_offset> + sizeof(struct hdfsFileInfo).
- *
- * So instead, we add the new fields to the hdfsExtendedFileInfo structure.
- * This structure is contained in the mOwner string found inside the
- * hdfsFileInfo. Specifically, the format of mOwner is:
- *
- * [owner-string] [null byte] [padding] [hdfsExtendedFileInfo structure]
- *
- * The padding is added so that the hdfsExtendedFileInfo structure starts on an
- * 8-byte boundary.
- *
- * @param str The string to locate the extended info in.
- * @return The offset of the hdfsExtendedFileInfo structure.
- */
-static size_t getExtendedFileInfoOffset(const char *str)
-{
- int num_64_bit_words = ((strlen(str) + 1) + 7) /
<TRUNCATED>
[17/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs.h
new file mode 100644
index 0000000..c1515d7
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs.h
@@ -0,0 +1,939 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_HDFS_H
+#define LIBHDFS_HDFS_H
+
+#include <errno.h> /* for EINTERNAL, etc. */
+#include <fcntl.h> /* for O_RDONLY, O_WRONLY */
+#include <stdint.h> /* for uint64_t, etc. */
+#include <time.h> /* for time_t */
+
+/*
+ * Support export of DLL symbols during libhdfs build, and import of DLL symbols
+ * during client application build. A client application may optionally define
+ * symbol LIBHDFS_DLL_IMPORT in its build. This is not strictly required, but
+ * the compiler can produce more efficient code with it.
+ */
+#ifdef WIN32
+ #ifdef LIBHDFS_DLL_EXPORT
+ #define LIBHDFS_EXTERNAL __declspec(dllexport)
+ #elif LIBHDFS_DLL_IMPORT
+ #define LIBHDFS_EXTERNAL __declspec(dllimport)
+ #else
+ #define LIBHDFS_EXTERNAL
+ #endif
+#else
+ #ifdef LIBHDFS_DLL_EXPORT
+ #define LIBHDFS_EXTERNAL __attribute__((visibility("default")))
+ #elif LIBHDFS_DLL_IMPORT
+ #define LIBHDFS_EXTERNAL __attribute__((visibility("default")))
+ #else
+ #define LIBHDFS_EXTERNAL
+ #endif
+#endif
+
+#ifndef O_RDONLY
+#define O_RDONLY 1
+#endif
+
+#ifndef O_WRONLY
+#define O_WRONLY 2
+#endif
+
+#ifndef EINTERNAL
+#define EINTERNAL 255
+#endif
+
+#define ELASTIC_BYTE_BUFFER_POOL_CLASS \
+ "org/apache/hadoop/io/ElasticByteBufferPool"
+
+/** All APIs set errno to meaningful values */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ /**
+ * Some utility decls used in libhdfs.
+ */
+ struct hdfsBuilder;
+ typedef int32_t tSize; /// size of data for read/write io ops
+ typedef time_t tTime; /// time type in seconds
+ typedef int64_t tOffset;/// offset within the file
+ typedef uint16_t tPort; /// port
+ typedef enum tObjectKind {
+ kObjectKindFile = 'F',
+ kObjectKindDirectory = 'D',
+ } tObjectKind;
+
+
+ /**
+ * The C reflection of org.apache.org.hadoop.FileSystem .
+ */
+ struct hdfs_internal;
+ typedef struct hdfs_internal* hdfsFS;
+
+ struct hdfsFile_internal;
+ typedef struct hdfsFile_internal* hdfsFile;
+
+ struct hadoopRzOptions;
+
+ struct hadoopRzBuffer;
+
+ /**
+ * Determine if a file is open for read.
+ *
+ * @param file The HDFS file
+ * @return 1 if the file is open for read; 0 otherwise
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsFileIsOpenForRead(hdfsFile file);
+
+ /**
+ * Determine if a file is open for write.
+ *
+ * @param file The HDFS file
+ * @return 1 if the file is open for write; 0 otherwise
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsFileIsOpenForWrite(hdfsFile file);
+
+ struct hdfsReadStatistics {
+ uint64_t totalBytesRead;
+ uint64_t totalLocalBytesRead;
+ uint64_t totalShortCircuitBytesRead;
+ uint64_t totalZeroCopyBytesRead;
+ };
+
+ /**
+ * Get read statistics about a file. This is only applicable to files
+ * opened for reading.
+ *
+ * @param file The HDFS file
+ * @param stats (out parameter) on a successful return, the read
+ * statistics. Unchanged otherwise. You must free the
+ * returned statistics with hdfsFileFreeReadStatistics.
+ * @return 0 if the statistics were successfully returned,
+ * -1 otherwise. On a failure, please check errno against
+ * ENOTSUP. webhdfs, LocalFilesystem, and so forth may
+ * not support read statistics.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsFileGetReadStatistics(hdfsFile file,
+ struct hdfsReadStatistics **stats);
+
+ /**
+ * @param stats HDFS read statistics for a file.
+ *
+ * @return the number of remote bytes read.
+ */
+ LIBHDFS_EXTERNAL
+ int64_t hdfsReadStatisticsGetRemoteBytesRead(
+ const struct hdfsReadStatistics *stats);
+
+ /**
+ * Clear the read statistics for a file.
+ *
+ * @param file The file to clear the read statistics of.
+ *
+ * @return 0 on success; the error code otherwise.
+ * EINVAL: the file is not open for reading.
+ * ENOTSUP: the file does not support clearing the read
+ * statistics.
+ * Errno will also be set to this code on failure.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsFileClearReadStatistics(hdfsFile file);
+
+ /**
+ * Free some HDFS read statistics.
+ *
+ * @param stats The HDFS read statistics to free.
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats);
+
+ /**
+ * hdfsConnectAsUser - Connect to a hdfs file system as a specific user
+ * Connect to the hdfs.
+ * @param nn The NameNode. See hdfsBuilderSetNameNode for details.
+ * @param port The port on which the server is listening.
+ * @param user the user name (this is hadoop domain user). Or NULL is equivelant to hhdfsConnect(host, port)
+ * @return Returns a handle to the filesystem or NULL on error.
+ * @deprecated Use hdfsBuilderConnect instead.
+ */
+ LIBHDFS_EXTERNAL
+ hdfsFS hdfsConnectAsUser(const char* nn, tPort port, const char *user);
+
+ /**
+ * hdfsConnect - Connect to a hdfs file system.
+ * Connect to the hdfs.
+ * @param nn The NameNode. See hdfsBuilderSetNameNode for details.
+ * @param port The port on which the server is listening.
+ * @return Returns a handle to the filesystem or NULL on error.
+ * @deprecated Use hdfsBuilderConnect instead.
+ */
+ LIBHDFS_EXTERNAL
+ hdfsFS hdfsConnect(const char* nn, tPort port);
+
+ /**
+ * hdfsConnect - Connect to an hdfs file system.
+ *
+ * Forces a new instance to be created
+ *
+ * @param nn The NameNode. See hdfsBuilderSetNameNode for details.
+ * @param port The port on which the server is listening.
+ * @param user The user name to use when connecting
+ * @return Returns a handle to the filesystem or NULL on error.
+ * @deprecated Use hdfsBuilderConnect instead.
+ */
+ LIBHDFS_EXTERNAL
+ hdfsFS hdfsConnectAsUserNewInstance(const char* nn, tPort port, const char *user );
+
+ /**
+ * hdfsConnect - Connect to an hdfs file system.
+ *
+ * Forces a new instance to be created
+ *
+ * @param nn The NameNode. See hdfsBuilderSetNameNode for details.
+ * @param port The port on which the server is listening.
+ * @return Returns a handle to the filesystem or NULL on error.
+ * @deprecated Use hdfsBuilderConnect instead.
+ */
+ LIBHDFS_EXTERNAL
+ hdfsFS hdfsConnectNewInstance(const char* nn, tPort port);
+
+ /**
+ * Connect to HDFS using the parameters defined by the builder.
+ *
+ * The HDFS builder will be freed, whether or not the connection was
+ * successful.
+ *
+ * Every successful call to hdfsBuilderConnect should be matched with a call
+ * to hdfsDisconnect, when the hdfsFS is no longer needed.
+ *
+ * @param bld The HDFS builder
+ * @return Returns a handle to the filesystem, or NULL on error.
+ */
+ LIBHDFS_EXTERNAL
+ hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld);
+
+ /**
+ * Create an HDFS builder.
+ *
+ * @return The HDFS builder, or NULL on error.
+ */
+ LIBHDFS_EXTERNAL
+ struct hdfsBuilder *hdfsNewBuilder(void);
+
+ /**
+ * Force the builder to always create a new instance of the FileSystem,
+ * rather than possibly finding one in the cache.
+ *
+ * @param bld The HDFS builder
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld);
+
+ /**
+ * Set the HDFS NameNode to connect to.
+ *
+ * @param bld The HDFS builder
+ * @param nn The NameNode to use.
+ *
+ * If the string given is 'default', the default NameNode
+ * configuration will be used (from the XML configuration files)
+ *
+ * If NULL is given, a LocalFileSystem will be created.
+ *
+ * If the string starts with a protocol type such as file:// or
+ * hdfs://, this protocol type will be used. If not, the
+ * hdfs:// protocol type will be used.
+ *
+ * You may specify a NameNode port in the usual way by
+ * passing a string of the format hdfs://<hostname>:<port>.
+ * Alternately, you may set the port with
+ * hdfsBuilderSetNameNodePort. However, you must not pass the
+ * port in two different ways.
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn);
+
+ /**
+ * Set the port of the HDFS NameNode to connect to.
+ *
+ * @param bld The HDFS builder
+ * @param port The port.
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port);
+
+ /**
+ * Set the username to use when connecting to the HDFS cluster.
+ *
+ * @param bld The HDFS builder
+ * @param userName The user name. The string will be shallow-copied.
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName);
+
+ /**
+ * Set the path to the Kerberos ticket cache to use when connecting to
+ * the HDFS cluster.
+ *
+ * @param bld The HDFS builder
+ * @param kerbTicketCachePath The Kerberos ticket cache path. The string
+ * will be shallow-copied.
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsBuilderSetKerbTicketCachePath(struct hdfsBuilder *bld,
+ const char *kerbTicketCachePath);
+
+ /**
+ * Free an HDFS builder.
+ *
+ * It is normally not necessary to call this function since
+ * hdfsBuilderConnect frees the builder.
+ *
+ * @param bld The HDFS builder
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsFreeBuilder(struct hdfsBuilder *bld);
+
+ /**
+ * Set a configuration string for an HdfsBuilder.
+ *
+ * @param key The key to set.
+ * @param val The value, or NULL to set no value.
+ * This will be shallow-copied. You are responsible for
+ * ensuring that it remains valid until the builder is
+ * freed.
+ *
+ * @return 0 on success; nonzero error code otherwise.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsBuilderConfSetStr(struct hdfsBuilder *bld, const char *key,
+ const char *val);
+
+ /**
+ * Get a configuration string.
+ *
+ * @param key The key to find
+ * @param val (out param) The value. This will be set to NULL if the
+ * key isn't found. You must free this string with
+ * hdfsConfStrFree.
+ *
+ * @return 0 on success; nonzero error code otherwise.
+ * Failure to find the key is not an error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsConfGetStr(const char *key, char **val);
+
+ /**
+ * Get a configuration integer.
+ *
+ * @param key The key to find
+ * @param val (out param) The value. This will NOT be changed if the
+ * key isn't found.
+ *
+ * @return 0 on success; nonzero error code otherwise.
+ * Failure to find the key is not an error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsConfGetInt(const char *key, int32_t *val);
+
+ /**
+ * Free a configuration string found with hdfsConfGetStr.
+ *
+ * @param val A configuration string obtained from hdfsConfGetStr
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsConfStrFree(char *val);
+
+ /**
+ * hdfsDisconnect - Disconnect from the hdfs file system.
+ * Disconnect from hdfs.
+ * @param fs The configured filesystem handle.
+ * @return Returns 0 on success, -1 on error.
+ * Even if there is an error, the resources associated with the
+ * hdfsFS will be freed.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsDisconnect(hdfsFS fs);
+
+
+ /**
+ * hdfsOpenFile - Open a hdfs file in given mode.
+ * @param fs The configured filesystem handle.
+ * @param path The full path to the file.
+ * @param flags - an | of bits/fcntl.h file flags - supported flags are O_RDONLY, O_WRONLY (meaning create or overwrite i.e., implies O_TRUNCAT),
+ * O_WRONLY|O_APPEND. Other flags are generally ignored other than (O_RDWR || (O_EXCL & O_CREAT)) which return NULL and set errno equal ENOTSUP.
+ * @param bufferSize Size of buffer for read/write - pass 0 if you want
+ * to use the default configured values.
+ * @param replication Block replication - pass 0 if you want to use
+ * the default configured values.
+ * @param blocksize Size of block - pass 0 if you want to use the
+ * default configured values.
+ * @return Returns the handle to the open file or NULL on error.
+ */
+ LIBHDFS_EXTERNAL
+ hdfsFile hdfsOpenFile(hdfsFS fs, const char* path, int flags,
+ int bufferSize, short replication, tSize blocksize);
+
+ /**
+ * hdfsTruncateFile - Truncate a hdfs file to given lenght.
+ * @param fs The configured filesystem handle.
+ * @param path The full path to the file.
+ * @param newlength The size the file is to be truncated to
+ * @return 1 if the file has been truncated to the desired newlength
+ * and is immediately available to be reused for write operations
+ * such as append.
+ * 0 if a background process of adjusting the length of the last
+ * block has been started, and clients should wait for it to
+ * complete before proceeding with further file updates.
+ * -1 on error.
+ */
+ int hdfsTruncateFile(hdfsFS fs, const char* path, tOffset newlength);
+
+ /**
+ * hdfsUnbufferFile - Reduce the buffering done on a file.
+ *
+ * @param file The file to unbuffer.
+ * @return 0 on success
+ * ENOTSUP if the file does not support unbuffering
+ * Errno will also be set to this value.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsUnbufferFile(hdfsFile file);
+
+ /**
+ * hdfsCloseFile - Close an open file.
+ * @param fs The configured filesystem handle.
+ * @param file The file handle.
+ * @return Returns 0 on success, -1 on error.
+ * On error, errno will be set appropriately.
+ * If the hdfs file was valid, the memory associated with it will
+ * be freed at the end of this call, even if there was an I/O
+ * error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsCloseFile(hdfsFS fs, hdfsFile file);
+
+
+ /**
+ * hdfsExists - Checks if a given path exsits on the filesystem
+ * @param fs The configured filesystem handle.
+ * @param path The path to look for
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsExists(hdfsFS fs, const char *path);
+
+
+ /**
+ * hdfsSeek - Seek to given offset in file.
+ * This works only for files opened in read-only mode.
+ * @param fs The configured filesystem handle.
+ * @param file The file handle.
+ * @param desiredPos Offset into the file to seek into.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsSeek(hdfsFS fs, hdfsFile file, tOffset desiredPos);
+
+
+ /**
+ * hdfsTell - Get the current offset in the file, in bytes.
+ * @param fs The configured filesystem handle.
+ * @param file The file handle.
+ * @return Current offset, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ tOffset hdfsTell(hdfsFS fs, hdfsFile file);
+
+
+ /**
+ * hdfsRead - Read data from an open file.
+ * @param fs The configured filesystem handle.
+ * @param file The file handle.
+ * @param buffer The buffer to copy read bytes into.
+ * @param length The length of the buffer.
+ * @return On success, a positive number indicating how many bytes
+ * were read.
+ * On end-of-file, 0.
+ * On error, -1. Errno will be set to the error code.
+ * Just like the POSIX read function, hdfsRead will return -1
+ * and set errno to EINTR if data is temporarily unavailable,
+ * but we are not yet at the end of the file.
+ */
+ LIBHDFS_EXTERNAL
+ tSize hdfsRead(hdfsFS fs, hdfsFile file, void* buffer, tSize length);
+
+ /**
+ * hdfsPread - Positional read of data from an open file.
+ * @param fs The configured filesystem handle.
+ * @param file The file handle.
+ * @param position Position from which to read
+ * @param buffer The buffer to copy read bytes into.
+ * @param length The length of the buffer.
+ * @return See hdfsRead
+ */
+ LIBHDFS_EXTERNAL
+ tSize hdfsPread(hdfsFS fs, hdfsFile file, tOffset position,
+ void* buffer, tSize length);
+
+
+ /**
+ * hdfsWrite - Write data into an open file.
+ * @param fs The configured filesystem handle.
+ * @param file The file handle.
+ * @param buffer The data.
+ * @param length The no. of bytes to write.
+ * @return Returns the number of bytes written, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ tSize hdfsWrite(hdfsFS fs, hdfsFile file, const void* buffer,
+ tSize length);
+
+
+ /**
+ * hdfsWrite - Flush the data.
+ * @param fs The configured filesystem handle.
+ * @param file The file handle.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsFlush(hdfsFS fs, hdfsFile file);
+
+
+ /**
+ * hdfsHFlush - Flush out the data in client's user buffer. After the
+ * return of this call, new readers will see the data.
+ * @param fs configured filesystem handle
+ * @param file file handle
+ * @return 0 on success, -1 on error and sets errno
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsHFlush(hdfsFS fs, hdfsFile file);
+
+
+ /**
+ * hdfsHSync - Similar to posix fsync, Flush out the data in client's
+ * user buffer. all the way to the disk device (but the disk may have
+ * it in its cache).
+ * @param fs configured filesystem handle
+ * @param file file handle
+ * @return 0 on success, -1 on error and sets errno
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsHSync(hdfsFS fs, hdfsFile file);
+
+
+ /**
+ * hdfsAvailable - Number of bytes that can be read from this
+ * input stream without blocking.
+ * @param fs The configured filesystem handle.
+ * @param file The file handle.
+ * @return Returns available bytes; -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsAvailable(hdfsFS fs, hdfsFile file);
+
+
+ /**
+ * hdfsCopy - Copy file from one filesystem to another.
+ * @param srcFS The handle to source filesystem.
+ * @param src The path of source file.
+ * @param dstFS The handle to destination filesystem.
+ * @param dst The path of destination file.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsCopy(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst);
+
+
+ /**
+ * hdfsMove - Move file from one filesystem to another.
+ * @param srcFS The handle to source filesystem.
+ * @param src The path of source file.
+ * @param dstFS The handle to destination filesystem.
+ * @param dst The path of destination file.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsMove(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst);
+
+
+ /**
+ * hdfsDelete - Delete file.
+ * @param fs The configured filesystem handle.
+ * @param path The path of the file.
+ * @param recursive if path is a directory and set to
+ * non-zero, the directory is deleted else throws an exception. In
+ * case of a file the recursive argument is irrelevant.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsDelete(hdfsFS fs, const char* path, int recursive);
+
+ /**
+ * hdfsRename - Rename file.
+ * @param fs The configured filesystem handle.
+ * @param oldPath The path of the source file.
+ * @param newPath The path of the destination file.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath);
+
+
+ /**
+ * hdfsGetWorkingDirectory - Get the current working directory for
+ * the given filesystem.
+ * @param fs The configured filesystem handle.
+ * @param buffer The user-buffer to copy path of cwd into.
+ * @param bufferSize The length of user-buffer.
+ * @return Returns buffer, NULL on error.
+ */
+ LIBHDFS_EXTERNAL
+ char* hdfsGetWorkingDirectory(hdfsFS fs, char *buffer, size_t bufferSize);
+
+
+ /**
+ * hdfsSetWorkingDirectory - Set the working directory. All relative
+ * paths will be resolved relative to it.
+ * @param fs The configured filesystem handle.
+ * @param path The path of the new 'cwd'.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsSetWorkingDirectory(hdfsFS fs, const char* path);
+
+
+ /**
+ * hdfsCreateDirectory - Make the given file and all non-existent
+ * parents into directories.
+ * @param fs The configured filesystem handle.
+ * @param path The path of the directory.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsCreateDirectory(hdfsFS fs, const char* path);
+
+
+ /**
+ * hdfsSetReplication - Set the replication of the specified
+ * file to the supplied value
+ * @param fs The configured filesystem handle.
+ * @param path The path of the file.
+ * @return Returns 0 on success, -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication);
+
+
+ /**
+ * hdfsFileInfo - Information about a file/directory.
+ */
+ typedef struct {
+ tObjectKind mKind; /* file or directory */
+ char *mName; /* the name of the file */
+ tTime mLastMod; /* the last modification time for the file in seconds */
+ tOffset mSize; /* the size of the file in bytes */
+ short mReplication; /* the count of replicas */
+ tOffset mBlockSize; /* the block size for the file */
+ char *mOwner; /* the owner of the file */
+ char *mGroup; /* the group associated with the file */
+ short mPermissions; /* the permissions associated with the file */
+ tTime mLastAccess; /* the last access time for the file in seconds */
+ } hdfsFileInfo;
+
+
+ /**
+ * hdfsListDirectory - Get list of files/directories for a given
+ * directory-path. hdfsFreeFileInfo should be called to deallocate memory.
+ * @param fs The configured filesystem handle.
+ * @param path The path of the directory.
+ * @param numEntries Set to the number of files/directories in path.
+ * @return Returns a dynamically-allocated array of hdfsFileInfo
+ * objects; NULL on error or empty directory.
+ * errno is set to non-zero on error or zero on success.
+ */
+ LIBHDFS_EXTERNAL
+ hdfsFileInfo *hdfsListDirectory(hdfsFS fs, const char* path,
+ int *numEntries);
+
+
+ /**
+ * hdfsGetPathInfo - Get information about a path as a (dynamically
+ * allocated) single hdfsFileInfo struct. hdfsFreeFileInfo should be
+ * called when the pointer is no longer needed.
+ * @param fs The configured filesystem handle.
+ * @param path The path of the file.
+ * @return Returns a dynamically-allocated hdfsFileInfo object;
+ * NULL on error.
+ */
+ LIBHDFS_EXTERNAL
+ hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path);
+
+
+ /**
+ * hdfsFreeFileInfo - Free up the hdfsFileInfo array (including fields)
+ * @param hdfsFileInfo The array of dynamically-allocated hdfsFileInfo
+ * objects.
+ * @param numEntries The size of the array.
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries);
+
+ /**
+ * hdfsFileIsEncrypted: determine if a file is encrypted based on its
+ * hdfsFileInfo.
+ * @return -1 if there was an error (errno will be set), 0 if the file is
+ * not encrypted, 1 if the file is encrypted.
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsFileIsEncrypted(hdfsFileInfo *hdfsFileInfo);
+
+
+ /**
+ * hdfsGetHosts - Get hostnames where a particular block (determined by
+ * pos & blocksize) of a file is stored. The last element in the array
+ * is NULL. Due to replication, a single block could be present on
+ * multiple hosts.
+ * @param fs The configured filesystem handle.
+ * @param path The path of the file.
+ * @param start The start of the block.
+ * @param length The length of the block.
+ * @return Returns a dynamically-allocated 2-d array of blocks-hosts;
+ * NULL on error.
+ */
+ LIBHDFS_EXTERNAL
+ char*** hdfsGetHosts(hdfsFS fs, const char* path,
+ tOffset start, tOffset length);
+
+
+ /**
+ * hdfsFreeHosts - Free up the structure returned by hdfsGetHosts
+ * @param hdfsFileInfo The array of dynamically-allocated hdfsFileInfo
+ * objects.
+ * @param numEntries The size of the array.
+ */
+ LIBHDFS_EXTERNAL
+ void hdfsFreeHosts(char ***blockHosts);
+
+
+ /**
+ * hdfsGetDefaultBlockSize - Get the default blocksize.
+ *
+ * @param fs The configured filesystem handle.
+ * @deprecated Use hdfsGetDefaultBlockSizeAtPath instead.
+ *
+ * @return Returns the default blocksize, or -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ tOffset hdfsGetDefaultBlockSize(hdfsFS fs);
+
+
+ /**
+ * hdfsGetDefaultBlockSizeAtPath - Get the default blocksize at the
+ * filesystem indicated by a given path.
+ *
+ * @param fs The configured filesystem handle.
+ * @param path The given path will be used to locate the actual
+ * filesystem. The full path does not have to exist.
+ *
+ * @return Returns the default blocksize, or -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ tOffset hdfsGetDefaultBlockSizeAtPath(hdfsFS fs, const char *path);
+
+
+ /**
+ * hdfsGetCapacity - Return the raw capacity of the filesystem.
+ * @param fs The configured filesystem handle.
+ * @return Returns the raw-capacity; -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ tOffset hdfsGetCapacity(hdfsFS fs);
+
+
+ /**
+ * hdfsGetUsed - Return the total raw size of all files in the filesystem.
+ * @param fs The configured filesystem handle.
+ * @return Returns the total-size; -1 on error.
+ */
+ LIBHDFS_EXTERNAL
+ tOffset hdfsGetUsed(hdfsFS fs);
+
+ /**
+ * Change the user and/or group of a file or directory.
+ *
+ * @param fs The configured filesystem handle.
+ * @param path the path to the file or directory
+ * @param owner User string. Set to NULL for 'no change'
+ * @param group Group string. Set to NULL for 'no change'
+ * @return 0 on success else -1
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsChown(hdfsFS fs, const char* path, const char *owner,
+ const char *group);
+
+ /**
+ * hdfsChmod
+ * @param fs The configured filesystem handle.
+ * @param path the path to the file or directory
+ * @param mode the bitmask to set it to
+ * @return 0 on success else -1
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsChmod(hdfsFS fs, const char* path, short mode);
+
+ /**
+ * hdfsUtime
+ * @param fs The configured filesystem handle.
+ * @param path the path to the file or directory
+ * @param mtime new modification time or -1 for no change
+ * @param atime new access time or -1 for no change
+ * @return 0 on success else -1
+ */
+ LIBHDFS_EXTERNAL
+ int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime);
+
+ /**
+ * Allocate a zero-copy options structure.
+ *
+ * You must free all options structures allocated with this function using
+ * hadoopRzOptionsFree.
+ *
+ * @return A zero-copy options structure, or NULL if one could
+ * not be allocated. If NULL is returned, errno will
+ * contain the error number.
+ */
+ LIBHDFS_EXTERNAL
+ struct hadoopRzOptions *hadoopRzOptionsAlloc(void);
+
+ /**
+ * Determine whether we should skip checksums in read0.
+ *
+ * @param opts The options structure.
+ * @param skip Nonzero to skip checksums sometimes; zero to always
+ * check them.
+ *
+ * @return 0 on success; -1 plus errno on failure.
+ */
+ LIBHDFS_EXTERNAL
+ int hadoopRzOptionsSetSkipChecksum(
+ struct hadoopRzOptions *opts, int skip);
+
+ /**
+ * Set the ByteBufferPool to use with read0.
+ *
+ * @param opts The options structure.
+ * @param className If this is NULL, we will not use any
+ * ByteBufferPool. If this is non-NULL, it will be
+ * treated as the name of the pool class to use.
+ * For example, you can use
+ * ELASTIC_BYTE_BUFFER_POOL_CLASS.
+ *
+ * @return 0 if the ByteBufferPool class was found and
+ * instantiated;
+ * -1 plus errno otherwise.
+ */
+ LIBHDFS_EXTERNAL
+ int hadoopRzOptionsSetByteBufferPool(
+ struct hadoopRzOptions *opts, const char *className);
+
+ /**
+ * Free a hadoopRzOptionsFree structure.
+ *
+ * @param opts The options structure to free.
+ * Any associated ByteBufferPool will also be freed.
+ */
+ LIBHDFS_EXTERNAL
+ void hadoopRzOptionsFree(struct hadoopRzOptions *opts);
+
+ /**
+ * Perform a byte buffer read.
+ * If possible, this will be a zero-copy (mmap) read.
+ *
+ * @param file The file to read from.
+ * @param opts An options structure created by hadoopRzOptionsAlloc.
+ * @param maxLength The maximum length to read. We may read fewer bytes
+ * than this length.
+ *
+ * @return On success, we will return a new hadoopRzBuffer.
+ * This buffer will continue to be valid and readable
+ * until it is released by readZeroBufferFree. Failure to
+ * release a buffer will lead to a memory leak.
+ * You can access the data within the hadoopRzBuffer with
+ * hadoopRzBufferGet. If you have reached EOF, the data
+ * within the hadoopRzBuffer will be NULL. You must still
+ * free hadoopRzBuffer instances containing NULL.
+ *
+ * On failure, we will return NULL plus an errno code.
+ * errno = EOPNOTSUPP indicates that we could not do a
+ * zero-copy read, and there was no ByteBufferPool
+ * supplied.
+ */
+ LIBHDFS_EXTERNAL
+ struct hadoopRzBuffer* hadoopReadZero(hdfsFile file,
+ struct hadoopRzOptions *opts, int32_t maxLength);
+
+ /**
+ * Determine the length of the buffer returned from readZero.
+ *
+ * @param buffer a buffer returned from readZero.
+ * @return the length of the buffer.
+ */
+ LIBHDFS_EXTERNAL
+ int32_t hadoopRzBufferLength(const struct hadoopRzBuffer *buffer);
+
+ /**
+ * Get a pointer to the raw buffer returned from readZero.
+ *
+ * To find out how many bytes this buffer contains, call
+ * hadoopRzBufferLength.
+ *
+ * @param buffer a buffer returned from readZero.
+ * @return a pointer to the start of the buffer. This will be
+ * NULL when end-of-file has been reached.
+ */
+ LIBHDFS_EXTERNAL
+ const void *hadoopRzBufferGet(const struct hadoopRzBuffer *buffer);
+
+ /**
+ * Release a buffer obtained through readZero.
+ *
+ * @param file The hdfs stream that created this buffer. This must be
+ * the same stream you called hadoopReadZero on.
+ * @param buffer The buffer to release.
+ */
+ LIBHDFS_EXTERNAL
+ void hadoopRzBufferFree(hdfsFile file, struct hadoopRzBuffer *buffer);
+
+#ifdef __cplusplus
+}
+#endif
+
+#undef LIBHDFS_EXTERNAL
+#endif /*LIBHDFS_HDFS_H*/
+
+/**
+ * vim: ts=4: sw=4: et
+ */
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs_test.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs_test.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs_test.h
new file mode 100644
index 0000000..0eab9a6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/hdfs_test.h
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_HDFS_TEST_H
+#define LIBHDFS_HDFS_TEST_H
+
+struct hdfsFile_internal;
+
+/**
+ * Some functions that are visible only for testing.
+ *
+ * This header is not meant to be exported or used outside of the libhdfs unit
+ * tests.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ /**
+ * Determine if a file is using the "direct read" optimization.
+ *
+ * @param file The HDFS file
+ * @return 1 if the file is using the direct read optimization,
+ * 0 otherwise.
+ */
+ int hdfsFileUsesDirectRead(struct hdfsFile_internal *file);
+
+ /**
+ * Disable the direct read optimization for a file.
+ *
+ * This is mainly provided for unit testing purposes.
+ *
+ * @param file The HDFS file
+ */
+ void hdfsFileDisableDirectRead(struct hdfsFile_internal *file);
+
+ /**
+ * Disable domain socket security checks.
+ *
+ * @param 0 if domain socket security was disabled;
+ * -1 if not.
+ */
+ int hdfsDisableDomainSocketSecurity(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/jni_helper.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/jni_helper.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/jni_helper.c
new file mode 100644
index 0000000..50d9681
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/jni_helper.c
@@ -0,0 +1,595 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "config.h"
+#include "exception.h"
+#include "jni_helper.h"
+#include "platform.h"
+#include "common/htable.h"
+#include "os/mutexes.h"
+#include "os/thread_local_storage.h"
+
+#include <stdio.h>
+#include <string.h>
+
+static struct htable *gClassRefHTable = NULL;
+
+/** The Native return types that methods could return */
+#define JVOID 'V'
+#define JOBJECT 'L'
+#define JARRAYOBJECT '['
+#define JBOOLEAN 'Z'
+#define JBYTE 'B'
+#define JCHAR 'C'
+#define JSHORT 'S'
+#define JINT 'I'
+#define JLONG 'J'
+#define JFLOAT 'F'
+#define JDOUBLE 'D'
+
+
+/**
+ * MAX_HASH_TABLE_ELEM: The maximum no. of entries in the hashtable.
+ * It's set to 4096 to account for (classNames + No. of threads)
+ */
+#define MAX_HASH_TABLE_ELEM 4096
+
+/**
+ * Length of buffer for retrieving created JVMs. (We only ever create one.)
+ */
+#define VM_BUF_LENGTH 1
+
+void destroyLocalReference(JNIEnv *env, jobject jObject)
+{
+ if (jObject)
+ (*env)->DeleteLocalRef(env, jObject);
+}
+
+static jthrowable validateMethodType(JNIEnv *env, MethType methType)
+{
+ if (methType != STATIC && methType != INSTANCE) {
+ return newRuntimeError(env, "validateMethodType(methType=%d): "
+ "illegal method type.\n", methType);
+ }
+ return NULL;
+}
+
+jthrowable newJavaStr(JNIEnv *env, const char *str, jstring *out)
+{
+ jstring jstr;
+
+ if (!str) {
+ /* Can't pass NULL to NewStringUTF: the result would be
+ * implementation-defined. */
+ *out = NULL;
+ return NULL;
+ }
+ jstr = (*env)->NewStringUTF(env, str);
+ if (!jstr) {
+ /* If NewStringUTF returns NULL, an exception has been thrown,
+ * which we need to handle. Probaly an OOM. */
+ return getPendingExceptionAndClear(env);
+ }
+ *out = jstr;
+ return NULL;
+}
+
+jthrowable newCStr(JNIEnv *env, jstring jstr, char **out)
+{
+ const char *tmp;
+
+ if (!jstr) {
+ *out = NULL;
+ return NULL;
+ }
+ tmp = (*env)->GetStringUTFChars(env, jstr, NULL);
+ if (!tmp) {
+ return getPendingExceptionAndClear(env);
+ }
+ *out = strdup(tmp);
+ (*env)->ReleaseStringUTFChars(env, jstr, tmp);
+ return NULL;
+}
+
+jthrowable invokeMethod(JNIEnv *env, jvalue *retval, MethType methType,
+ jobject instObj, const char *className,
+ const char *methName, const char *methSignature, ...)
+{
+ va_list args;
+ jclass cls;
+ jmethodID mid;
+ jthrowable jthr;
+ const char *str;
+ char returnType;
+
+ jthr = validateMethodType(env, methType);
+ if (jthr)
+ return jthr;
+ jthr = globalClassReference(className, env, &cls);
+ if (jthr)
+ return jthr;
+ jthr = methodIdFromClass(className, methName, methSignature,
+ methType, env, &mid);
+ if (jthr)
+ return jthr;
+ str = methSignature;
+ while (*str != ')') str++;
+ str++;
+ returnType = *str;
+ va_start(args, methSignature);
+ if (returnType == JOBJECT || returnType == JARRAYOBJECT) {
+ jobject jobj = NULL;
+ if (methType == STATIC) {
+ jobj = (*env)->CallStaticObjectMethodV(env, cls, mid, args);
+ }
+ else if (methType == INSTANCE) {
+ jobj = (*env)->CallObjectMethodV(env, instObj, mid, args);
+ }
+ retval->l = jobj;
+ }
+ else if (returnType == JVOID) {
+ if (methType == STATIC) {
+ (*env)->CallStaticVoidMethodV(env, cls, mid, args);
+ }
+ else if (methType == INSTANCE) {
+ (*env)->CallVoidMethodV(env, instObj, mid, args);
+ }
+ }
+ else if (returnType == JBOOLEAN) {
+ jboolean jbool = 0;
+ if (methType == STATIC) {
+ jbool = (*env)->CallStaticBooleanMethodV(env, cls, mid, args);
+ }
+ else if (methType == INSTANCE) {
+ jbool = (*env)->CallBooleanMethodV(env, instObj, mid, args);
+ }
+ retval->z = jbool;
+ }
+ else if (returnType == JSHORT) {
+ jshort js = 0;
+ if (methType == STATIC) {
+ js = (*env)->CallStaticShortMethodV(env, cls, mid, args);
+ }
+ else if (methType == INSTANCE) {
+ js = (*env)->CallShortMethodV(env, instObj, mid, args);
+ }
+ retval->s = js;
+ }
+ else if (returnType == JLONG) {
+ jlong jl = -1;
+ if (methType == STATIC) {
+ jl = (*env)->CallStaticLongMethodV(env, cls, mid, args);
+ }
+ else if (methType == INSTANCE) {
+ jl = (*env)->CallLongMethodV(env, instObj, mid, args);
+ }
+ retval->j = jl;
+ }
+ else if (returnType == JINT) {
+ jint ji = -1;
+ if (methType == STATIC) {
+ ji = (*env)->CallStaticIntMethodV(env, cls, mid, args);
+ }
+ else if (methType == INSTANCE) {
+ ji = (*env)->CallIntMethodV(env, instObj, mid, args);
+ }
+ retval->i = ji;
+ }
+ va_end(args);
+
+ jthr = (*env)->ExceptionOccurred(env);
+ if (jthr) {
+ (*env)->ExceptionClear(env);
+ return jthr;
+ }
+ return NULL;
+}
+
+jthrowable constructNewObjectOfClass(JNIEnv *env, jobject *out, const char *className,
+ const char *ctorSignature, ...)
+{
+ va_list args;
+ jclass cls;
+ jmethodID mid;
+ jobject jobj;
+ jthrowable jthr;
+
+ jthr = globalClassReference(className, env, &cls);
+ if (jthr)
+ return jthr;
+ jthr = methodIdFromClass(className, "<init>", ctorSignature,
+ INSTANCE, env, &mid);
+ if (jthr)
+ return jthr;
+ va_start(args, ctorSignature);
+ jobj = (*env)->NewObjectV(env, cls, mid, args);
+ va_end(args);
+ if (!jobj)
+ return getPendingExceptionAndClear(env);
+ *out = jobj;
+ return NULL;
+}
+
+
+jthrowable methodIdFromClass(const char *className, const char *methName,
+ const char *methSignature, MethType methType,
+ JNIEnv *env, jmethodID *out)
+{
+ jclass cls;
+ jthrowable jthr;
+ jmethodID mid = 0;
+
+ jthr = globalClassReference(className, env, &cls);
+ if (jthr)
+ return jthr;
+ jthr = validateMethodType(env, methType);
+ if (jthr)
+ return jthr;
+ if (methType == STATIC) {
+ mid = (*env)->GetStaticMethodID(env, cls, methName, methSignature);
+ }
+ else if (methType == INSTANCE) {
+ mid = (*env)->GetMethodID(env, cls, methName, methSignature);
+ }
+ if (mid == NULL) {
+ fprintf(stderr, "could not find method %s from class %s with "
+ "signature %s\n", methName, className, methSignature);
+ return getPendingExceptionAndClear(env);
+ }
+ *out = mid;
+ return NULL;
+}
+
+jthrowable globalClassReference(const char *className, JNIEnv *env, jclass *out)
+{
+ jthrowable jthr = NULL;
+ jclass local_clazz = NULL;
+ jclass clazz = NULL;
+ int ret;
+
+ mutexLock(&hdfsHashMutex);
+ if (!gClassRefHTable) {
+ gClassRefHTable = htable_alloc(MAX_HASH_TABLE_ELEM, ht_hash_string,
+ ht_compare_string);
+ if (!gClassRefHTable) {
+ jthr = newRuntimeError(env, "htable_alloc failed\n");
+ goto done;
+ }
+ }
+ clazz = htable_get(gClassRefHTable, className);
+ if (clazz) {
+ *out = clazz;
+ goto done;
+ }
+ local_clazz = (*env)->FindClass(env,className);
+ if (!local_clazz) {
+ jthr = getPendingExceptionAndClear(env);
+ goto done;
+ }
+ clazz = (*env)->NewGlobalRef(env, local_clazz);
+ if (!clazz) {
+ jthr = getPendingExceptionAndClear(env);
+ goto done;
+ }
+ ret = htable_put(gClassRefHTable, (void*)className, clazz);
+ if (ret) {
+ jthr = newRuntimeError(env, "htable_put failed with error "
+ "code %d\n", ret);
+ goto done;
+ }
+ *out = clazz;
+ jthr = NULL;
+done:
+ mutexUnlock(&hdfsHashMutex);
+ (*env)->DeleteLocalRef(env, local_clazz);
+ if (jthr && clazz) {
+ (*env)->DeleteGlobalRef(env, clazz);
+ }
+ return jthr;
+}
+
+jthrowable classNameOfObject(jobject jobj, JNIEnv *env, char **name)
+{
+ jthrowable jthr;
+ jclass cls, clsClass = NULL;
+ jmethodID mid;
+ jstring str = NULL;
+ const char *cstr = NULL;
+ char *newstr;
+
+ cls = (*env)->GetObjectClass(env, jobj);
+ if (cls == NULL) {
+ jthr = getPendingExceptionAndClear(env);
+ goto done;
+ }
+ clsClass = (*env)->FindClass(env, "java/lang/Class");
+ if (clsClass == NULL) {
+ jthr = getPendingExceptionAndClear(env);
+ goto done;
+ }
+ mid = (*env)->GetMethodID(env, clsClass, "getName", "()Ljava/lang/String;");
+ if (mid == NULL) {
+ jthr = getPendingExceptionAndClear(env);
+ goto done;
+ }
+ str = (*env)->CallObjectMethod(env, cls, mid);
+ if (str == NULL) {
+ jthr = getPendingExceptionAndClear(env);
+ goto done;
+ }
+ cstr = (*env)->GetStringUTFChars(env, str, NULL);
+ if (!cstr) {
+ jthr = getPendingExceptionAndClear(env);
+ goto done;
+ }
+ newstr = strdup(cstr);
+ if (newstr == NULL) {
+ jthr = newRuntimeError(env, "classNameOfObject: out of memory");
+ goto done;
+ }
+ *name = newstr;
+ jthr = NULL;
+
+done:
+ destroyLocalReference(env, cls);
+ destroyLocalReference(env, clsClass);
+ if (str) {
+ if (cstr)
+ (*env)->ReleaseStringUTFChars(env, str, cstr);
+ (*env)->DeleteLocalRef(env, str);
+ }
+ return jthr;
+}
+
+
+/**
+ * Get the global JNI environemnt.
+ *
+ * We only have to create the JVM once. After that, we can use it in
+ * every thread. You must be holding the jvmMutex when you call this
+ * function.
+ *
+ * @return The JNIEnv on success; error code otherwise
+ */
+static JNIEnv* getGlobalJNIEnv(void)
+{
+ JavaVM* vmBuf[VM_BUF_LENGTH];
+ JNIEnv *env;
+ jint rv = 0;
+ jint noVMs = 0;
+ jthrowable jthr;
+ char *hadoopClassPath;
+ const char *hadoopClassPathVMArg = "-Djava.class.path=";
+ size_t optHadoopClassPathLen;
+ char *optHadoopClassPath;
+ int noArgs = 1;
+ char *hadoopJvmArgs;
+ char jvmArgDelims[] = " ";
+ char *str, *token, *savePtr;
+ JavaVMInitArgs vm_args;
+ JavaVM *vm;
+ JavaVMOption *options;
+
+ rv = JNI_GetCreatedJavaVMs(&(vmBuf[0]), VM_BUF_LENGTH, &noVMs);
+ if (rv != 0) {
+ fprintf(stderr, "JNI_GetCreatedJavaVMs failed with error: %d\n", rv);
+ return NULL;
+ }
+
+ if (noVMs == 0) {
+ //Get the environment variables for initializing the JVM
+ hadoopClassPath = getenv("CLASSPATH");
+ if (hadoopClassPath == NULL) {
+ fprintf(stderr, "Environment variable CLASSPATH not set!\n");
+ return NULL;
+ }
+ optHadoopClassPathLen = strlen(hadoopClassPath) +
+ strlen(hadoopClassPathVMArg) + 1;
+ optHadoopClassPath = malloc(sizeof(char)*optHadoopClassPathLen);
+ snprintf(optHadoopClassPath, optHadoopClassPathLen,
+ "%s%s", hadoopClassPathVMArg, hadoopClassPath);
+
+ // Determine the # of LIBHDFS_OPTS args
+ hadoopJvmArgs = getenv("LIBHDFS_OPTS");
+ if (hadoopJvmArgs != NULL) {
+ hadoopJvmArgs = strdup(hadoopJvmArgs);
+ for (noArgs = 1, str = hadoopJvmArgs; ; noArgs++, str = NULL) {
+ token = strtok_r(str, jvmArgDelims, &savePtr);
+ if (NULL == token) {
+ break;
+ }
+ }
+ free(hadoopJvmArgs);
+ }
+
+ // Now that we know the # args, populate the options array
+ options = calloc(noArgs, sizeof(JavaVMOption));
+ if (!options) {
+ fputs("Call to calloc failed\n", stderr);
+ free(optHadoopClassPath);
+ return NULL;
+ }
+ options[0].optionString = optHadoopClassPath;
+ hadoopJvmArgs = getenv("LIBHDFS_OPTS");
+ if (hadoopJvmArgs != NULL) {
+ hadoopJvmArgs = strdup(hadoopJvmArgs);
+ for (noArgs = 1, str = hadoopJvmArgs; ; noArgs++, str = NULL) {
+ token = strtok_r(str, jvmArgDelims, &savePtr);
+ if (NULL == token) {
+ break;
+ }
+ options[noArgs].optionString = token;
+ }
+ }
+
+ //Create the VM
+ vm_args.version = JNI_VERSION_1_2;
+ vm_args.options = options;
+ vm_args.nOptions = noArgs;
+ vm_args.ignoreUnrecognized = 1;
+
+ rv = JNI_CreateJavaVM(&vm, (void*)&env, &vm_args);
+
+ if (hadoopJvmArgs != NULL) {
+ free(hadoopJvmArgs);
+ }
+ free(optHadoopClassPath);
+ free(options);
+
+ if (rv != 0) {
+ fprintf(stderr, "Call to JNI_CreateJavaVM failed "
+ "with error: %d\n", rv);
+ return NULL;
+ }
+ jthr = invokeMethod(env, NULL, STATIC, NULL,
+ "org/apache/hadoop/fs/FileSystem",
+ "loadFileSystems", "()V");
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL, "loadFileSystems");
+ }
+ }
+ else {
+ //Attach this thread to the VM
+ vm = vmBuf[0];
+ rv = (*vm)->AttachCurrentThread(vm, (void*)&env, 0);
+ if (rv != 0) {
+ fprintf(stderr, "Call to AttachCurrentThread "
+ "failed with error: %d\n", rv);
+ return NULL;
+ }
+ }
+
+ return env;
+}
+
+/**
+ * getJNIEnv: A helper function to get the JNIEnv* for the given thread.
+ * If no JVM exists, then one will be created. JVM command line arguments
+ * are obtained from the LIBHDFS_OPTS environment variable.
+ *
+ * Implementation note: we rely on POSIX thread-local storage (tls).
+ * This allows us to associate a destructor function with each thread, that
+ * will detach the thread from the Java VM when the thread terminates. If we
+ * failt to do this, it will cause a memory leak.
+ *
+ * However, POSIX TLS is not the most efficient way to do things. It requires a
+ * key to be initialized before it can be used. Since we don't know if this key
+ * is initialized at the start of this function, we have to lock a mutex first
+ * and check. Luckily, most operating systems support the more efficient
+ * __thread construct, which is initialized by the linker.
+ *
+ * @param: None.
+ * @return The JNIEnv* corresponding to the thread.
+ */
+JNIEnv* getJNIEnv(void)
+{
+ JNIEnv *env;
+ THREAD_LOCAL_STORAGE_GET_QUICK();
+ mutexLock(&jvmMutex);
+ if (threadLocalStorageGet(&env)) {
+ mutexUnlock(&jvmMutex);
+ return NULL;
+ }
+ if (env) {
+ mutexUnlock(&jvmMutex);
+ return env;
+ }
+
+ env = getGlobalJNIEnv();
+ mutexUnlock(&jvmMutex);
+ if (!env) {
+ fprintf(stderr, "getJNIEnv: getGlobalJNIEnv failed\n");
+ return NULL;
+ }
+ if (threadLocalStorageSet(env)) {
+ return NULL;
+ }
+ THREAD_LOCAL_STORAGE_SET_QUICK(env);
+ return env;
+}
+
+int javaObjectIsOfClass(JNIEnv *env, jobject obj, const char *name)
+{
+ jclass clazz;
+ int ret;
+
+ clazz = (*env)->FindClass(env, name);
+ if (!clazz) {
+ printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "javaObjectIsOfClass(%s)", name);
+ return -1;
+ }
+ ret = (*env)->IsInstanceOf(env, obj, clazz);
+ (*env)->DeleteLocalRef(env, clazz);
+ return ret == JNI_TRUE ? 1 : 0;
+}
+
+jthrowable hadoopConfSetStr(JNIEnv *env, jobject jConfiguration,
+ const char *key, const char *value)
+{
+ jthrowable jthr;
+ jstring jkey = NULL, jvalue = NULL;
+
+ jthr = newJavaStr(env, key, &jkey);
+ if (jthr)
+ goto done;
+ jthr = newJavaStr(env, value, &jvalue);
+ if (jthr)
+ goto done;
+ jthr = invokeMethod(env, NULL, INSTANCE, jConfiguration,
+ "org/apache/hadoop/conf/Configuration", "set",
+ "(Ljava/lang/String;Ljava/lang/String;)V",
+ jkey, jvalue);
+ if (jthr)
+ goto done;
+done:
+ (*env)->DeleteLocalRef(env, jkey);
+ (*env)->DeleteLocalRef(env, jvalue);
+ return jthr;
+}
+
+jthrowable fetchEnumInstance(JNIEnv *env, const char *className,
+ const char *valueName, jobject *out)
+{
+ jclass clazz;
+ jfieldID fieldId;
+ jobject jEnum;
+ char prettyClass[256];
+
+ clazz = (*env)->FindClass(env, className);
+ if (!clazz) {
+ return newRuntimeError(env, "fetchEnum(%s, %s): failed to find class.",
+ className, valueName);
+ }
+ if (snprintf(prettyClass, sizeof(prettyClass), "L%s;", className)
+ >= sizeof(prettyClass)) {
+ return newRuntimeError(env, "fetchEnum(%s, %s): class name too long.",
+ className, valueName);
+ }
+ fieldId = (*env)->GetStaticFieldID(env, clazz, valueName, prettyClass);
+ if (!fieldId) {
+ return getPendingExceptionAndClear(env);
+ }
+ jEnum = (*env)->GetStaticObjectField(env, clazz, fieldId);
+ if (!jEnum) {
+ return getPendingExceptionAndClear(env);
+ }
+ *out = jEnum;
+ return NULL;
+}
+
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/jni_helper.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/jni_helper.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/jni_helper.h
new file mode 100644
index 0000000..90accc7
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/jni_helper.h
@@ -0,0 +1,161 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_JNI_HELPER_H
+#define LIBHDFS_JNI_HELPER_H
+
+#include <jni.h>
+#include <stdio.h>
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <errno.h>
+
+#define PATH_SEPARATOR ':'
+
+
+/** Denote the method we want to invoke as STATIC or INSTANCE */
+typedef enum {
+ STATIC,
+ INSTANCE
+} MethType;
+
+/**
+ * Create a new malloc'ed C string from a Java string.
+ *
+ * @param env The JNI environment
+ * @param jstr The Java string
+ * @param out (out param) the malloc'ed C string
+ *
+ * @return NULL on success; the exception otherwise
+ */
+jthrowable newCStr(JNIEnv *env, jstring jstr, char **out);
+
+/**
+ * Create a new Java string from a C string.
+ *
+ * @param env The JNI environment
+ * @param str The C string
+ * @param out (out param) the java string
+ *
+ * @return NULL on success; the exception otherwise
+ */
+jthrowable newJavaStr(JNIEnv *env, const char *str, jstring *out);
+
+/**
+ * Helper function to destroy a local reference of java.lang.Object
+ * @param env: The JNIEnv pointer.
+ * @param jFile: The local reference of java.lang.Object object
+ * @return None.
+ */
+void destroyLocalReference(JNIEnv *env, jobject jObject);
+
+/** invokeMethod: Invoke a Static or Instance method.
+ * className: Name of the class where the method can be found
+ * methName: Name of the method
+ * methSignature: the signature of the method "(arg-types)ret-type"
+ * methType: The type of the method (STATIC or INSTANCE)
+ * instObj: Required if the methType is INSTANCE. The object to invoke
+ the method on.
+ * env: The JNIEnv pointer
+ * retval: The pointer to a union type which will contain the result of the
+ method invocation, e.g. if the method returns an Object, retval will be
+ set to that, if the method returns boolean, retval will be set to the
+ value (JNI_TRUE or JNI_FALSE), etc.
+ * exc: If the methods throws any exception, this will contain the reference
+ * Arguments (the method arguments) must be passed after methSignature
+ * RETURNS: -1 on error and 0 on success. If -1 is returned, exc will have
+ a valid exception reference, and the result stored at retval is undefined.
+ */
+jthrowable invokeMethod(JNIEnv *env, jvalue *retval, MethType methType,
+ jobject instObj, const char *className, const char *methName,
+ const char *methSignature, ...);
+
+jthrowable constructNewObjectOfClass(JNIEnv *env, jobject *out, const char *className,
+ const char *ctorSignature, ...);
+
+jthrowable methodIdFromClass(const char *className, const char *methName,
+ const char *methSignature, MethType methType,
+ JNIEnv *env, jmethodID *out);
+
+jthrowable globalClassReference(const char *className, JNIEnv *env, jclass *out);
+
+/** classNameOfObject: Get an object's class name.
+ * @param jobj: The object.
+ * @param env: The JNIEnv pointer.
+ * @param name: (out param) On success, will contain a string containing the
+ * class name. This string must be freed by the caller.
+ * @return NULL on success, or the exception
+ */
+jthrowable classNameOfObject(jobject jobj, JNIEnv *env, char **name);
+
+/** getJNIEnv: A helper function to get the JNIEnv* for the given thread.
+ * If no JVM exists, then one will be created. JVM command line arguments
+ * are obtained from the LIBHDFS_OPTS environment variable.
+ * @param: None.
+ * @return The JNIEnv* corresponding to the thread.
+ * */
+JNIEnv* getJNIEnv(void);
+
+/**
+ * Figure out if a Java object is an instance of a particular class.
+ *
+ * @param env The Java environment.
+ * @param obj The object to check.
+ * @param name The class name to check.
+ *
+ * @return -1 if we failed to find the referenced class name.
+ * 0 if the object is not of the given class.
+ * 1 if the object is of the given class.
+ */
+int javaObjectIsOfClass(JNIEnv *env, jobject obj, const char *name);
+
+/**
+ * Set a value in a configuration object.
+ *
+ * @param env The JNI environment
+ * @param jConfiguration The configuration object to modify
+ * @param key The key to modify
+ * @param value The value to set the key to
+ *
+ * @return NULL on success; exception otherwise
+ */
+jthrowable hadoopConfSetStr(JNIEnv *env, jobject jConfiguration,
+ const char *key, const char *value);
+
+/**
+ * Fetch an instance of an Enum.
+ *
+ * @param env The JNI environment.
+ * @param className The enum class name.
+ * @param valueName The name of the enum value
+ * @param out (out param) on success, a local reference to an
+ * instance of the enum object. (Since Java enums are
+ * singletones, this is also the only instance.)
+ *
+ * @return NULL on success; exception otherwise
+ */
+jthrowable fetchEnumInstance(JNIEnv *env, const char *className,
+ const char *valueName, jobject *out);
+
+#endif /*LIBHDFS_JNI_HELPER_H*/
+
+/**
+ * vim: ts=4: sw=4: et:
+ */
+
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/native_mini_dfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/native_mini_dfs.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/native_mini_dfs.c
new file mode 100644
index 0000000..b36ef76
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/native_mini_dfs.c
@@ -0,0 +1,357 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "exception.h"
+#include "jni_helper.h"
+#include "native_mini_dfs.h"
+#include "platform.h"
+
+#include <errno.h>
+#include <jni.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#ifndef EINTERNAL
+#define EINTERNAL 255
+#endif
+
+#define MINIDFS_CLUSTER_BUILDER "org/apache/hadoop/hdfs/MiniDFSCluster$Builder"
+#define MINIDFS_CLUSTER "org/apache/hadoop/hdfs/MiniDFSCluster"
+#define HADOOP_CONF "org/apache/hadoop/conf/Configuration"
+#define HADOOP_NAMENODE "org/apache/hadoop/hdfs/server/namenode/NameNode"
+#define JAVA_INETSOCKETADDRESS "java/net/InetSocketAddress"
+
+struct NativeMiniDfsCluster {
+ /**
+ * The NativeMiniDfsCluster object
+ */
+ jobject obj;
+
+ /**
+ * Path to the domain socket, or the empty string if there is none.
+ */
+ char domainSocketPath[PATH_MAX];
+};
+
+static int hdfsDisableDomainSocketSecurity(void)
+{
+ jthrowable jthr;
+ JNIEnv* env = getJNIEnv();
+ if (env == NULL) {
+ errno = EINTERNAL;
+ return -1;
+ }
+ jthr = invokeMethod(env, NULL, STATIC, NULL,
+ "org/apache/hadoop/net/unix/DomainSocket",
+ "disableBindPathValidation", "()V");
+ if (jthr) {
+ errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "DomainSocket#disableBindPathValidation");
+ return -1;
+ }
+ return 0;
+}
+
+static jthrowable nmdConfigureShortCircuit(JNIEnv *env,
+ struct NativeMiniDfsCluster *cl, jobject cobj)
+{
+ jthrowable jthr;
+ char *tmpDir;
+
+ int ret = hdfsDisableDomainSocketSecurity();
+ if (ret) {
+ return newRuntimeError(env, "failed to disable hdfs domain "
+ "socket security: error %d", ret);
+ }
+ jthr = hadoopConfSetStr(env, cobj, "dfs.client.read.shortcircuit", "true");
+ if (jthr) {
+ return jthr;
+ }
+ tmpDir = getenv("TMPDIR");
+ if (!tmpDir) {
+ tmpDir = "/tmp";
+ }
+ snprintf(cl->domainSocketPath, PATH_MAX, "%s/native_mini_dfs.sock.%d.%d",
+ tmpDir, getpid(), rand());
+ snprintf(cl->domainSocketPath, PATH_MAX, "%s/native_mini_dfs.sock.%d.%d",
+ tmpDir, getpid(), rand());
+ jthr = hadoopConfSetStr(env, cobj, "dfs.domain.socket.path",
+ cl->domainSocketPath);
+ if (jthr) {
+ return jthr;
+ }
+ return NULL;
+}
+
+struct NativeMiniDfsCluster* nmdCreate(struct NativeMiniDfsConf *conf)
+{
+ struct NativeMiniDfsCluster* cl = NULL;
+ jobject bld = NULL, cobj = NULL, cluster = NULL;
+ jvalue val;
+ JNIEnv *env = getJNIEnv();
+ jthrowable jthr;
+ jstring jconfStr = NULL;
+
+ if (!env) {
+ fprintf(stderr, "nmdCreate: unable to construct JNIEnv.\n");
+ return NULL;
+ }
+ cl = calloc(1, sizeof(struct NativeMiniDfsCluster));
+ if (!cl) {
+ fprintf(stderr, "nmdCreate: OOM");
+ goto error;
+ }
+ jthr = constructNewObjectOfClass(env, &cobj, HADOOP_CONF, "()V");
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdCreate: new Configuration");
+ goto error;
+ }
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdCreate: Configuration::setBoolean");
+ goto error;
+ }
+ // Disable 'minimum block size' -- it's annoying in tests.
+ (*env)->DeleteLocalRef(env, jconfStr);
+ jconfStr = NULL;
+ jthr = newJavaStr(env, "dfs.namenode.fs-limits.min-block-size", &jconfStr);
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdCreate: new String");
+ goto error;
+ }
+ jthr = invokeMethod(env, NULL, INSTANCE, cobj, HADOOP_CONF,
+ "setLong", "(Ljava/lang/String;J)V", jconfStr, 0LL);
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdCreate: Configuration::setLong");
+ goto error;
+ }
+ // Creae MiniDFSCluster object
+ jthr = constructNewObjectOfClass(env, &bld, MINIDFS_CLUSTER_BUILDER,
+ "(L"HADOOP_CONF";)V", cobj);
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdCreate: NativeMiniDfsCluster#Builder#Builder");
+ goto error;
+ }
+ if (conf->configureShortCircuit) {
+ jthr = nmdConfigureShortCircuit(env, cl, cobj);
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdCreate: nmdConfigureShortCircuit error");
+ goto error;
+ }
+ }
+ jthr = invokeMethod(env, &val, INSTANCE, bld, MINIDFS_CLUSTER_BUILDER,
+ "format", "(Z)L" MINIDFS_CLUSTER_BUILDER ";", conf->doFormat);
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL, "nmdCreate: "
+ "Builder::format");
+ goto error;
+ }
+ (*env)->DeleteLocalRef(env, val.l);
+ if (conf->webhdfsEnabled) {
+ jthr = invokeMethod(env, &val, INSTANCE, bld, MINIDFS_CLUSTER_BUILDER,
+ "nameNodeHttpPort", "(I)L" MINIDFS_CLUSTER_BUILDER ";",
+ conf->namenodeHttpPort);
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL, "nmdCreate: "
+ "Builder::nameNodeHttpPort");
+ goto error;
+ }
+ (*env)->DeleteLocalRef(env, val.l);
+ }
+ jthr = invokeMethod(env, &val, INSTANCE, bld, MINIDFS_CLUSTER_BUILDER,
+ "build", "()L" MINIDFS_CLUSTER ";");
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdCreate: Builder#build");
+ goto error;
+ }
+ cluster = val.l;
+ cl->obj = (*env)->NewGlobalRef(env, val.l);
+ if (!cl->obj) {
+ printPendingExceptionAndFree(env, PRINT_EXC_ALL,
+ "nmdCreate: NewGlobalRef");
+ goto error;
+ }
+ (*env)->DeleteLocalRef(env, cluster);
+ (*env)->DeleteLocalRef(env, bld);
+ (*env)->DeleteLocalRef(env, cobj);
+ (*env)->DeleteLocalRef(env, jconfStr);
+ return cl;
+
+error:
+ (*env)->DeleteLocalRef(env, cluster);
+ (*env)->DeleteLocalRef(env, bld);
+ (*env)->DeleteLocalRef(env, cobj);
+ (*env)->DeleteLocalRef(env, jconfStr);
+ free(cl);
+ return NULL;
+}
+
+void nmdFree(struct NativeMiniDfsCluster* cl)
+{
+ JNIEnv *env = getJNIEnv();
+ if (!env) {
+ fprintf(stderr, "nmdFree: getJNIEnv failed\n");
+ free(cl);
+ return;
+ }
+ (*env)->DeleteGlobalRef(env, cl->obj);
+ free(cl);
+}
+
+int nmdShutdown(struct NativeMiniDfsCluster* cl)
+{
+ JNIEnv *env = getJNIEnv();
+ jthrowable jthr;
+
+ if (!env) {
+ fprintf(stderr, "nmdShutdown: getJNIEnv failed\n");
+ return -EIO;
+ }
+ jthr = invokeMethod(env, NULL, INSTANCE, cl->obj,
+ MINIDFS_CLUSTER, "shutdown", "()V");
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdShutdown: MiniDFSCluster#shutdown");
+ return -EIO;
+ }
+ return 0;
+}
+
+int nmdWaitClusterUp(struct NativeMiniDfsCluster *cl)
+{
+ jthrowable jthr;
+ JNIEnv *env = getJNIEnv();
+ if (!env) {
+ fprintf(stderr, "nmdWaitClusterUp: getJNIEnv failed\n");
+ return -EIO;
+ }
+ jthr = invokeMethod(env, NULL, INSTANCE, cl->obj,
+ MINIDFS_CLUSTER, "waitClusterUp", "()V");
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdWaitClusterUp: MiniDFSCluster#waitClusterUp ");
+ return -EIO;
+ }
+ return 0;
+}
+
+int nmdGetNameNodePort(const struct NativeMiniDfsCluster *cl)
+{
+ JNIEnv *env = getJNIEnv();
+ jvalue jVal;
+ jthrowable jthr;
+
+ if (!env) {
+ fprintf(stderr, "nmdHdfsConnect: getJNIEnv failed\n");
+ return -EIO;
+ }
+ // Note: this will have to be updated when HA nativeMiniDfs clusters are
+ // supported
+ jthr = invokeMethod(env, &jVal, INSTANCE, cl->obj,
+ MINIDFS_CLUSTER, "getNameNodePort", "()I");
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdHdfsConnect: MiniDFSCluster#getNameNodePort");
+ return -EIO;
+ }
+ return jVal.i;
+}
+
+int nmdGetNameNodeHttpAddress(const struct NativeMiniDfsCluster *cl,
+ int *port, const char **hostName)
+{
+ JNIEnv *env = getJNIEnv();
+ jvalue jVal;
+ jobject jNameNode, jAddress;
+ jthrowable jthr;
+ int ret = 0;
+ const char *host;
+
+ if (!env) {
+ fprintf(stderr, "nmdHdfsConnect: getJNIEnv failed\n");
+ return -EIO;
+ }
+ // First get the (first) NameNode of the cluster
+ jthr = invokeMethod(env, &jVal, INSTANCE, cl->obj, MINIDFS_CLUSTER,
+ "getNameNode", "()L" HADOOP_NAMENODE ";");
+ if (jthr) {
+ printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdGetNameNodeHttpAddress: "
+ "MiniDFSCluster#getNameNode");
+ return -EIO;
+ }
+ jNameNode = jVal.l;
+
+ // Then get the http address (InetSocketAddress) of the NameNode
+ jthr = invokeMethod(env, &jVal, INSTANCE, jNameNode, HADOOP_NAMENODE,
+ "getHttpAddress", "()L" JAVA_INETSOCKETADDRESS ";");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdGetNameNodeHttpAddress: "
+ "NameNode#getHttpAddress");
+ goto error_dlr_nn;
+ }
+ jAddress = jVal.l;
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jAddress,
+ JAVA_INETSOCKETADDRESS, "getPort", "()I");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdGetNameNodeHttpAddress: "
+ "InetSocketAddress#getPort");
+ goto error_dlr_addr;
+ }
+ *port = jVal.i;
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jAddress, JAVA_INETSOCKETADDRESS,
+ "getHostName", "()Ljava/lang/String;");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "nmdGetNameNodeHttpAddress: "
+ "InetSocketAddress#getHostName");
+ goto error_dlr_addr;
+ }
+ host = (*env)->GetStringUTFChars(env, jVal.l, NULL);
+ *hostName = strdup(host);
+ (*env)->ReleaseStringUTFChars(env, jVal.l, host);
+
+error_dlr_addr:
+ (*env)->DeleteLocalRef(env, jAddress);
+error_dlr_nn:
+ (*env)->DeleteLocalRef(env, jNameNode);
+
+ return ret;
+}
+
+const char *hdfsGetDomainSocketPath(const struct NativeMiniDfsCluster *cl) {
+ if (cl->domainSocketPath[0]) {
+ return cl->domainSocketPath;
+ }
+
+ return NULL;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/native_mini_dfs.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/native_mini_dfs.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/native_mini_dfs.h
new file mode 100644
index 0000000..ce8b1cf
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/native_mini_dfs.h
@@ -0,0 +1,129 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_NATIVE_MINI_DFS_H
+#define LIBHDFS_NATIVE_MINI_DFS_H
+
+#include <jni.h> /* for jboolean */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct hdfsBuilder;
+struct NativeMiniDfsCluster;
+
+/**
+ * Represents a configuration to use for creating a Native MiniDFSCluster
+ */
+struct NativeMiniDfsConf {
+ /**
+ * Nonzero if the cluster should be formatted prior to startup.
+ */
+ jboolean doFormat;
+
+ /**
+ * Whether or not to enable webhdfs in MiniDfsCluster
+ */
+ jboolean webhdfsEnabled;
+
+ /**
+ * The http port of the namenode in MiniDfsCluster
+ */
+ jint namenodeHttpPort;
+
+ /**
+ * Nonzero if we should configure short circuit.
+ */
+ jboolean configureShortCircuit;
+};
+
+/**
+ * Create a NativeMiniDfsBuilder
+ *
+ * @param conf (inout) The cluster configuration
+ *
+ * @return a NativeMiniDfsBuilder, or a NULL pointer on error.
+ */
+struct NativeMiniDfsCluster* nmdCreate(struct NativeMiniDfsConf *conf);
+
+/**
+ * Wait until a MiniDFSCluster comes out of safe mode.
+ *
+ * @param cl The cluster
+ *
+ * @return 0 on success; a non-zero error code if the cluster fails to
+ * come out of safe mode.
+ */
+int nmdWaitClusterUp(struct NativeMiniDfsCluster *cl);
+
+/**
+ * Shut down a NativeMiniDFS cluster
+ *
+ * @param cl The cluster
+ *
+ * @return 0 on success; a non-zero error code if an exception is
+ * thrown.
+ */
+int nmdShutdown(struct NativeMiniDfsCluster *cl);
+
+/**
+ * Destroy a Native MiniDFSCluster
+ *
+ * @param cl The cluster to destroy
+ */
+void nmdFree(struct NativeMiniDfsCluster* cl);
+
+/**
+ * Get the port that's in use by the given (non-HA) nativeMiniDfs
+ *
+ * @param cl The initialized NativeMiniDfsCluster
+ *
+ * @return the port, or a negative error code
+ */
+int nmdGetNameNodePort(const struct NativeMiniDfsCluster *cl);
+
+/**
+ * Get the http address that's in use by the given (non-HA) nativeMiniDfs
+ *
+ * @param cl The initialized NativeMiniDfsCluster
+ * @param port Used to capture the http port of the NameNode
+ * of the NativeMiniDfsCluster
+ * @param hostName Used to capture the http hostname of the NameNode
+ * of the NativeMiniDfsCluster
+ *
+ * @return 0 on success; a non-zero error code if failing to
+ * get the information.
+ */
+int nmdGetNameNodeHttpAddress(const struct NativeMiniDfsCluster *cl,
+ int *port, const char **hostName);
+
+/**
+ * Get domain socket path set for this cluster.
+ *
+ * @param cl The cluster
+ *
+ * @return A const string of domain socket path, or NULL if not set.
+ */
+const char *hdfsGetDomainSocketPath(const struct NativeMiniDfsCluster *cl);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/mutexes.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/mutexes.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/mutexes.h
new file mode 100644
index 0000000..da30bf4
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/mutexes.h
@@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_MUTEXES_H
+#define LIBHDFS_MUTEXES_H
+
+/*
+ * Defines abstraction over platform-specific mutexes. libhdfs has no formal
+ * initialization function that users would call from a single-threaded context
+ * to initialize the library. This creates a challenge for bootstrapping the
+ * mutexes. To address this, all required mutexes are pre-defined here with
+ * external storage. Platform-specific implementations must guarantee that the
+ * mutexes are initialized via static initialization.
+ */
+
+#include "platform.h"
+
+/** Mutex protecting the class reference hash table. */
+extern mutex hdfsHashMutex;
+
+/** Mutex protecting singleton JVM instance. */
+extern mutex jvmMutex;
+
+/**
+ * Locks a mutex.
+ *
+ * @param m mutex
+ * @return 0 if successful, non-zero otherwise
+ */
+int mutexLock(mutex *m);
+
+/**
+ * Unlocks a mutex.
+ *
+ * @param m mutex
+ * @return 0 if successful, non-zero otherwise
+ */
+int mutexUnlock(mutex *m);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/mutexes.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/mutexes.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/mutexes.c
new file mode 100644
index 0000000..c4c2f26
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/mutexes.c
@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "os/mutexes.h"
+
+#include <pthread.h>
+#include <stdio.h>
+
+mutex hdfsHashMutex = PTHREAD_MUTEX_INITIALIZER;
+mutex jvmMutex = PTHREAD_MUTEX_INITIALIZER;
+
+int mutexLock(mutex *m) {
+ int ret = pthread_mutex_lock(m);
+ if (ret) {
+ fprintf(stderr, "mutexLock: pthread_mutex_lock failed with error %d\n",
+ ret);
+ }
+ return ret;
+}
+
+int mutexUnlock(mutex *m) {
+ int ret = pthread_mutex_unlock(m);
+ if (ret) {
+ fprintf(stderr, "mutexUnlock: pthread_mutex_unlock failed with error %d\n",
+ ret);
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/platform.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/platform.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/platform.h
new file mode 100644
index 0000000..c63bbf9
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/platform.h
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_PLATFORM_H
+#define LIBHDFS_PLATFORM_H
+
+#include <pthread.h>
+
+/* Use gcc type-checked format arguments. */
+#define TYPE_CHECKED_PRINTF_FORMAT(formatArg, varArgs) \
+ __attribute__((format(printf, formatArg, varArgs)))
+
+/*
+ * Mutex and thread data types defined by pthreads.
+ */
+typedef pthread_mutex_t mutex;
+typedef pthread_t threadId;
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/thread.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/thread.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/thread.c
new file mode 100644
index 0000000..af0c61f
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/os/posix/thread.c
@@ -0,0 +1,52 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "os/thread.h"
+
+#include <pthread.h>
+#include <stdio.h>
+
+/**
+ * Defines a helper function that adapts function pointer provided by caller to
+ * the type required by pthread_create.
+ *
+ * @param toRun thread to run
+ * @return void* result of running thread (always NULL)
+ */
+static void* runThread(void *toRun) {
+ const thread *t = toRun;
+ t->start(t->arg);
+ return NULL;
+}
+
+int threadCreate(thread *t) {
+ int ret;
+ ret = pthread_create(&t->id, NULL, runThread, t);
+ if (ret) {
+ fprintf(stderr, "threadCreate: pthread_create failed with error %d\n", ret);
+ }
+ return ret;
+}
+
+int threadJoin(const thread *t) {
+ int ret = pthread_join(t->id, NULL);
+ if (ret) {
+ fprintf(stderr, "threadJoin: pthread_join failed with error %d\n", ret);
+ }
+ return ret;
+}
[06/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/vecsum.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/vecsum.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/vecsum.c
deleted file mode 100644
index 80a64b4..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/vecsum.c
+++ /dev/null
@@ -1,825 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <sys/resource.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <time.h>
-#include <unistd.h>
-
-#ifdef __MACH__ // OS X does not have clock_gettime
-#include <mach/clock.h>
-#include <mach/mach.h>
-#include <mach/mach_time.h>
-#endif
-
-#include "config.h"
-#include "hdfs.h"
-
-#define VECSUM_CHUNK_SIZE (8 * 1024 * 1024)
-#define ZCR_READ_CHUNK_SIZE (1024 * 1024 * 8)
-#define NORMAL_READ_CHUNK_SIZE (8 * 1024 * 1024)
-#define DOUBLES_PER_LOOP_ITER 16
-
-static double timespec_to_double(const struct timespec *ts)
-{
- double sec = ts->tv_sec;
- double nsec = ts->tv_nsec;
- return sec + (nsec / 1000000000L);
-}
-
-struct stopwatch {
- struct timespec start;
- struct timespec stop;
-};
-
-
-#ifdef __MACH__
-static int clock_gettime_mono(struct timespec * ts) {
- static mach_timebase_info_data_t tb;
- static uint64_t timestart = 0;
- uint64_t t = 0;
- if (timestart == 0) {
- mach_timebase_info(&tb);
- timestart = mach_absolute_time();
- }
- t = mach_absolute_time() - timestart;
- t *= tb.numer;
- t /= tb.denom;
- ts->tv_sec = t / 1000000000ULL;
- ts->tv_nsec = t - (ts->tv_sec * 1000000000ULL);
- return 0;
-}
-#else
-static int clock_gettime_mono(struct timespec * ts) {
- return clock_gettime(CLOCK_MONOTONIC, ts);
-}
-#endif
-
-static struct stopwatch *stopwatch_create(void)
-{
- struct stopwatch *watch;
-
- watch = calloc(1, sizeof(struct stopwatch));
- if (!watch) {
- fprintf(stderr, "failed to allocate memory for stopwatch\n");
- goto error;
- }
- if (clock_gettime_mono(&watch->start)) {
- int err = errno;
- fprintf(stderr, "clock_gettime(CLOCK_MONOTONIC) failed with "
- "error %d (%s)\n", err, strerror(err));
- goto error;
- }
- return watch;
-
-error:
- free(watch);
- return NULL;
-}
-
-static void stopwatch_stop(struct stopwatch *watch,
- long long bytes_read)
-{
- double elapsed, rate;
-
- if (clock_gettime_mono(&watch->stop)) {
- int err = errno;
- fprintf(stderr, "clock_gettime(CLOCK_MONOTONIC) failed with "
- "error %d (%s)\n", err, strerror(err));
- goto done;
- }
- elapsed = timespec_to_double(&watch->stop) -
- timespec_to_double(&watch->start);
- rate = (bytes_read / elapsed) / (1024 * 1024 * 1024);
- printf("stopwatch: took %.5g seconds to read %lld bytes, "
- "for %.5g GB/s\n", elapsed, bytes_read, rate);
- printf("stopwatch: %.5g seconds\n", elapsed);
-done:
- free(watch);
-}
-
-enum vecsum_type {
- VECSUM_LOCAL = 0,
- VECSUM_LIBHDFS,
- VECSUM_ZCR,
-};
-
-#define VECSUM_TYPE_VALID_VALUES "libhdfs, zcr, or local"
-
-int parse_vecsum_type(const char *str)
-{
- if (strcasecmp(str, "local") == 0)
- return VECSUM_LOCAL;
- else if (strcasecmp(str, "libhdfs") == 0)
- return VECSUM_LIBHDFS;
- else if (strcasecmp(str, "zcr") == 0)
- return VECSUM_ZCR;
- else
- return -1;
-}
-
-struct options {
- // The path to read.
- const char *path;
-
- // Length of the file.
- long long length;
-
- // The number of times to read the path.
- int passes;
-
- // Type of vecsum to do
- enum vecsum_type ty;
-
- // RPC address to use for HDFS
- const char *rpc_address;
-};
-
-static struct options *options_create(void)
-{
- struct options *opts = NULL;
- const char *pass_str;
- const char *ty_str;
- const char *length_str;
- int ty;
-
- opts = calloc(1, sizeof(struct options));
- if (!opts) {
- fprintf(stderr, "failed to calloc options\n");
- goto error;
- }
- opts->path = getenv("VECSUM_PATH");
- if (!opts->path) {
- fprintf(stderr, "You must set the VECSUM_PATH environment "
- "variable to the path of the file to read.\n");
- goto error;
- }
- length_str = getenv("VECSUM_LENGTH");
- if (!length_str) {
- length_str = "2147483648";
- }
- opts->length = atoll(length_str);
- if (!opts->length) {
- fprintf(stderr, "Can't parse VECSUM_LENGTH of '%s'.\n",
- length_str);
- goto error;
- }
- if (opts->length % VECSUM_CHUNK_SIZE) {
- fprintf(stderr, "VECSUM_LENGTH must be a multiple of '%lld'. The "
- "currently specified length of '%lld' is not.\n",
- (long long)VECSUM_CHUNK_SIZE, (long long)opts->length);
- goto error;
- }
- pass_str = getenv("VECSUM_PASSES");
- if (!pass_str) {
- fprintf(stderr, "You must set the VECSUM_PASSES environment "
- "variable to the number of passes to make.\n");
- goto error;
- }
- opts->passes = atoi(pass_str);
- if (opts->passes <= 0) {
- fprintf(stderr, "Invalid value for the VECSUM_PASSES "
- "environment variable. You must set this to a "
- "number greater than 0.\n");
- goto error;
- }
- ty_str = getenv("VECSUM_TYPE");
- if (!ty_str) {
- fprintf(stderr, "You must set the VECSUM_TYPE environment "
- "variable to " VECSUM_TYPE_VALID_VALUES "\n");
- goto error;
- }
- ty = parse_vecsum_type(ty_str);
- if (ty < 0) {
- fprintf(stderr, "Invalid VECSUM_TYPE environment variable. "
- "Valid values are " VECSUM_TYPE_VALID_VALUES "\n");
- goto error;
- }
- opts->ty = ty;
- opts->rpc_address = getenv("VECSUM_RPC_ADDRESS");
- if (!opts->rpc_address) {
- opts->rpc_address = "default";
- }
- return opts;
-error:
- free(opts);
- return NULL;
-}
-
-static int test_file_chunk_setup(double **chunk)
-{
- int i;
- double *c, val;
-
- c = malloc(VECSUM_CHUNK_SIZE);
- if (!c) {
- fprintf(stderr, "test_file_create: failed to malloc "
- "a buffer of size '%lld'\n",
- (long long) VECSUM_CHUNK_SIZE);
- return EIO;
- }
- val = 0.0;
- for (i = 0; i < VECSUM_CHUNK_SIZE / sizeof(double); i++) {
- c[i] = val;
- val += 0.5;
- }
- *chunk = c;
- return 0;
-}
-
-static void options_free(struct options *opts)
-{
- free(opts);
-}
-
-struct local_data {
- int fd;
- double *mmap;
- long long length;
-};
-
-static int local_data_create_file(struct local_data *cdata,
- const struct options *opts)
-{
- int ret = EIO;
- int dup_fd = -1;
- FILE *fp = NULL;
- double *chunk = NULL;
- long long offset = 0;
-
- dup_fd = dup(cdata->fd);
- if (dup_fd < 0) {
- ret = errno;
- fprintf(stderr, "local_data_create_file: dup failed: %s (%d)\n",
- strerror(ret), ret);
- goto done;
- }
- fp = fdopen(dup_fd, "w");
- if (!fp) {
- ret = errno;
- fprintf(stderr, "local_data_create_file: fdopen failed: %s (%d)\n",
- strerror(ret), ret);
- goto done;
- }
- ret = test_file_chunk_setup(&chunk);
- if (ret)
- goto done;
- while (offset < opts->length) {
- if (fwrite(chunk, VECSUM_CHUNK_SIZE, 1, fp) != 1) {
- fprintf(stderr, "local_data_create_file: failed to write to "
- "the local file '%s' at offset %lld\n",
- opts->path, offset);
- ret = EIO;
- goto done;
- }
- offset += VECSUM_CHUNK_SIZE;
- }
- fprintf(stderr, "local_data_create_file: successfully re-wrote %s as "
- "a file of length %lld\n", opts->path, opts->length);
- ret = 0;
-
-done:
- if (dup_fd >= 0) {
- close(dup_fd);
- }
- if (fp) {
- fclose(fp);
- }
- free(chunk);
- return ret;
-}
-
-static struct local_data *local_data_create(const struct options *opts)
-{
- struct local_data *cdata = NULL;
- struct stat st_buf;
-
- cdata = malloc(sizeof(*cdata));
- if (!cdata) {
- fprintf(stderr, "Failed to allocate local test data.\n");
- goto error;
- }
- cdata->fd = -1;
- cdata->mmap = MAP_FAILED;
- cdata->length = opts->length;
-
- cdata->fd = open(opts->path, O_RDWR | O_CREAT, 0777);
- if (cdata->fd < 0) {
- int err = errno;
- fprintf(stderr, "local_data_create: failed to open %s "
- "for read/write: error %d (%s)\n", opts->path, err, strerror(err));
- goto error;
- }
- if (fstat(cdata->fd, &st_buf)) {
- int err = errno;
- fprintf(stderr, "local_data_create: fstat(%s) failed: "
- "error %d (%s)\n", opts->path, err, strerror(err));
- goto error;
- }
- if (st_buf.st_size != opts->length) {
- int err;
- fprintf(stderr, "local_data_create: current size of %s is %lld, but "
- "we want %lld. Re-writing the file.\n",
- opts->path, (long long)st_buf.st_size,
- (long long)opts->length);
- err = local_data_create_file(cdata, opts);
- if (err)
- goto error;
- }
- cdata->mmap = mmap(NULL, cdata->length, PROT_READ,
- MAP_PRIVATE, cdata->fd, 0);
- if (cdata->mmap == MAP_FAILED) {
- int err = errno;
- fprintf(stderr, "local_data_create: mmap(%s) failed: "
- "error %d (%s)\n", opts->path, err, strerror(err));
- goto error;
- }
- return cdata;
-
-error:
- if (cdata) {
- if (cdata->fd >= 0) {
- close(cdata->fd);
- }
- free(cdata);
- }
- return NULL;
-}
-
-static void local_data_free(struct local_data *cdata)
-{
- close(cdata->fd);
- munmap(cdata->mmap, cdata->length);
-}
-
-struct libhdfs_data {
- hdfsFS fs;
- hdfsFile file;
- long long length;
- double *buf;
-};
-
-static void libhdfs_data_free(struct libhdfs_data *ldata)
-{
- if (ldata->fs) {
- free(ldata->buf);
- if (ldata->file) {
- hdfsCloseFile(ldata->fs, ldata->file);
- }
- hdfsDisconnect(ldata->fs);
- }
- free(ldata);
-}
-
-static int libhdfs_data_create_file(struct libhdfs_data *ldata,
- const struct options *opts)
-{
- int ret;
- double *chunk = NULL;
- long long offset = 0;
-
- ldata->file = hdfsOpenFile(ldata->fs, opts->path, O_WRONLY, 0, 1, 0);
- if (!ldata->file) {
- ret = errno;
- fprintf(stderr, "libhdfs_data_create_file: hdfsOpenFile(%s, "
- "O_WRONLY) failed: error %d (%s)\n", opts->path, ret,
- strerror(ret));
- goto done;
- }
- ret = test_file_chunk_setup(&chunk);
- if (ret)
- goto done;
- while (offset < opts->length) {
- ret = hdfsWrite(ldata->fs, ldata->file, chunk, VECSUM_CHUNK_SIZE);
- if (ret < 0) {
- ret = errno;
- fprintf(stderr, "libhdfs_data_create_file: got error %d (%s) at "
- "offset %lld of %s\n", ret, strerror(ret),
- offset, opts->path);
- goto done;
- } else if (ret < VECSUM_CHUNK_SIZE) {
- fprintf(stderr, "libhdfs_data_create_file: got short write "
- "of %d at offset %lld of %s\n", ret, offset, opts->path);
- goto done;
- }
- offset += VECSUM_CHUNK_SIZE;
- }
- ret = 0;
-done:
- free(chunk);
- if (ldata->file) {
- if (hdfsCloseFile(ldata->fs, ldata->file)) {
- fprintf(stderr, "libhdfs_data_create_file: hdfsCloseFile error.");
- ret = EIO;
- }
- ldata->file = NULL;
- }
- return ret;
-}
-
-static struct libhdfs_data *libhdfs_data_create(const struct options *opts)
-{
- struct libhdfs_data *ldata = NULL;
- struct hdfsBuilder *builder = NULL;
- hdfsFileInfo *pinfo = NULL;
-
- ldata = calloc(1, sizeof(struct libhdfs_data));
- if (!ldata) {
- fprintf(stderr, "Failed to allocate libhdfs test data.\n");
- goto error;
- }
- builder = hdfsNewBuilder();
- if (!builder) {
- fprintf(stderr, "Failed to create builder.\n");
- goto error;
- }
- hdfsBuilderSetNameNode(builder, opts->rpc_address);
- hdfsBuilderConfSetStr(builder,
- "dfs.client.read.shortcircuit.skip.checksum", "true");
- ldata->fs = hdfsBuilderConnect(builder);
- if (!ldata->fs) {
- fprintf(stderr, "Could not connect to default namenode!\n");
- goto error;
- }
- pinfo = hdfsGetPathInfo(ldata->fs, opts->path);
- if (!pinfo) {
- int err = errno;
- fprintf(stderr, "hdfsGetPathInfo(%s) failed: error %d (%s). "
- "Attempting to re-create file.\n",
- opts->path, err, strerror(err));
- if (libhdfs_data_create_file(ldata, opts))
- goto error;
- } else if (pinfo->mSize != opts->length) {
- fprintf(stderr, "hdfsGetPathInfo(%s) failed: length was %lld, "
- "but we want length %lld. Attempting to re-create file.\n",
- opts->path, (long long)pinfo->mSize, (long long)opts->length);
- if (libhdfs_data_create_file(ldata, opts))
- goto error;
- }
- ldata->file = hdfsOpenFile(ldata->fs, opts->path, O_RDONLY, 0, 0, 0);
- if (!ldata->file) {
- int err = errno;
- fprintf(stderr, "hdfsOpenFile(%s) failed: error %d (%s)\n",
- opts->path, err, strerror(err));
- goto error;
- }
- ldata->length = opts->length;
- return ldata;
-
-error:
- if (pinfo)
- hdfsFreeFileInfo(pinfo, 1);
- if (ldata)
- libhdfs_data_free(ldata);
- return NULL;
-}
-
-static int check_byte_size(int byte_size, const char *const str)
-{
- if (byte_size % sizeof(double)) {
- fprintf(stderr, "%s is not a multiple "
- "of sizeof(double)\n", str);
- return EINVAL;
- }
- if ((byte_size / sizeof(double)) % DOUBLES_PER_LOOP_ITER) {
- fprintf(stderr, "The number of doubles contained in "
- "%s is not a multiple of DOUBLES_PER_LOOP_ITER\n",
- str);
- return EINVAL;
- }
- return 0;
-}
-
-#ifdef HAVE_INTEL_SSE_INTRINSICS
-
-#include <emmintrin.h>
-
-static double vecsum(const double *buf, int num_doubles)
-{
- int i;
- double hi, lo;
- __m128d x0, x1, x2, x3, x4, x5, x6, x7;
- __m128d sum0 = _mm_set_pd(0.0,0.0);
- __m128d sum1 = _mm_set_pd(0.0,0.0);
- __m128d sum2 = _mm_set_pd(0.0,0.0);
- __m128d sum3 = _mm_set_pd(0.0,0.0);
- __m128d sum4 = _mm_set_pd(0.0,0.0);
- __m128d sum5 = _mm_set_pd(0.0,0.0);
- __m128d sum6 = _mm_set_pd(0.0,0.0);
- __m128d sum7 = _mm_set_pd(0.0,0.0);
- for (i = 0; i < num_doubles; i+=DOUBLES_PER_LOOP_ITER) {
- x0 = _mm_load_pd(buf + i + 0);
- x1 = _mm_load_pd(buf + i + 2);
- x2 = _mm_load_pd(buf + i + 4);
- x3 = _mm_load_pd(buf + i + 6);
- x4 = _mm_load_pd(buf + i + 8);
- x5 = _mm_load_pd(buf + i + 10);
- x6 = _mm_load_pd(buf + i + 12);
- x7 = _mm_load_pd(buf + i + 14);
- sum0 = _mm_add_pd(sum0, x0);
- sum1 = _mm_add_pd(sum1, x1);
- sum2 = _mm_add_pd(sum2, x2);
- sum3 = _mm_add_pd(sum3, x3);
- sum4 = _mm_add_pd(sum4, x4);
- sum5 = _mm_add_pd(sum5, x5);
- sum6 = _mm_add_pd(sum6, x6);
- sum7 = _mm_add_pd(sum7, x7);
- }
- x0 = _mm_add_pd(sum0, sum1);
- x1 = _mm_add_pd(sum2, sum3);
- x2 = _mm_add_pd(sum4, sum5);
- x3 = _mm_add_pd(sum6, sum7);
- x4 = _mm_add_pd(x0, x1);
- x5 = _mm_add_pd(x2, x3);
- x6 = _mm_add_pd(x4, x5);
- _mm_storeh_pd(&hi, x6);
- _mm_storel_pd(&lo, x6);
- return hi + lo;
-}
-
-#else
-
-static double vecsum(const double *buf, int num_doubles)
-{
- int i;
- double sum = 0.0;
- for (i = 0; i < num_doubles; i++) {
- sum += buf[i];
- }
- return sum;
-}
-
-#endif
-
-static int vecsum_zcr_loop(int pass, struct libhdfs_data *ldata,
- struct hadoopRzOptions *zopts,
- const struct options *opts)
-{
- int32_t len;
- double sum = 0.0;
- const double *buf;
- struct hadoopRzBuffer *rzbuf = NULL;
- int ret;
-
- while (1) {
- rzbuf = hadoopReadZero(ldata->file, zopts, ZCR_READ_CHUNK_SIZE);
- if (!rzbuf) {
- ret = errno;
- fprintf(stderr, "hadoopReadZero failed with error "
- "code %d (%s)\n", ret, strerror(ret));
- goto done;
- }
- buf = hadoopRzBufferGet(rzbuf);
- if (!buf) break;
- len = hadoopRzBufferLength(rzbuf);
- if (len < ZCR_READ_CHUNK_SIZE) {
- fprintf(stderr, "hadoopReadZero got a partial read "
- "of length %d\n", len);
- ret = EINVAL;
- goto done;
- }
- sum += vecsum(buf,
- ZCR_READ_CHUNK_SIZE / sizeof(double));
- hadoopRzBufferFree(ldata->file, rzbuf);
- }
- printf("finished zcr pass %d. sum = %g\n", pass, sum);
- ret = 0;
-
-done:
- if (rzbuf)
- hadoopRzBufferFree(ldata->file, rzbuf);
- return ret;
-}
-
-static int vecsum_zcr(struct libhdfs_data *ldata,
- const struct options *opts)
-{
- int ret, pass;
- struct hadoopRzOptions *zopts = NULL;
-
- zopts = hadoopRzOptionsAlloc();
- if (!zopts) {
- fprintf(stderr, "hadoopRzOptionsAlloc failed.\n");
- ret = ENOMEM;
- goto done;
- }
- if (hadoopRzOptionsSetSkipChecksum(zopts, 1)) {
- ret = errno;
- perror("hadoopRzOptionsSetSkipChecksum failed: ");
- goto done;
- }
- if (hadoopRzOptionsSetByteBufferPool(zopts, NULL)) {
- ret = errno;
- perror("hadoopRzOptionsSetByteBufferPool failed: ");
- goto done;
- }
- for (pass = 0; pass < opts->passes; ++pass) {
- ret = vecsum_zcr_loop(pass, ldata, zopts, opts);
- if (ret) {
- fprintf(stderr, "vecsum_zcr_loop pass %d failed "
- "with error %d\n", pass, ret);
- goto done;
- }
- hdfsSeek(ldata->fs, ldata->file, 0);
- }
- ret = 0;
-done:
- if (zopts)
- hadoopRzOptionsFree(zopts);
- return ret;
-}
-
-tSize hdfsReadFully(hdfsFS fs, hdfsFile f, void* buffer, tSize length)
-{
- uint8_t *buf = buffer;
- tSize ret, nread = 0;
-
- while (length > 0) {
- ret = hdfsRead(fs, f, buf, length);
- if (ret < 0) {
- if (errno != EINTR) {
- return -1;
- }
- }
- if (ret == 0) {
- break;
- }
- nread += ret;
- length -= ret;
- buf += ret;
- }
- return nread;
-}
-
-static int vecsum_normal_loop(int pass, const struct libhdfs_data *ldata,
- const struct options *opts)
-{
- double sum = 0.0;
-
- while (1) {
- int res = hdfsReadFully(ldata->fs, ldata->file, ldata->buf,
- NORMAL_READ_CHUNK_SIZE);
- if (res == 0) // EOF
- break;
- if (res < 0) {
- int err = errno;
- fprintf(stderr, "hdfsRead failed with error %d (%s)\n",
- err, strerror(err));
- return err;
- }
- if (res < NORMAL_READ_CHUNK_SIZE) {
- fprintf(stderr, "hdfsRead got a partial read of "
- "length %d\n", res);
- return EINVAL;
- }
- sum += vecsum(ldata->buf,
- NORMAL_READ_CHUNK_SIZE / sizeof(double));
- }
- printf("finished normal pass %d. sum = %g\n", pass, sum);
- return 0;
-}
-
-static int vecsum_libhdfs(struct libhdfs_data *ldata,
- const struct options *opts)
-{
- int pass;
-
- ldata->buf = malloc(NORMAL_READ_CHUNK_SIZE);
- if (!ldata->buf) {
- fprintf(stderr, "failed to malloc buffer of size %d\n",
- NORMAL_READ_CHUNK_SIZE);
- return ENOMEM;
- }
- for (pass = 0; pass < opts->passes; ++pass) {
- int ret = vecsum_normal_loop(pass, ldata, opts);
- if (ret) {
- fprintf(stderr, "vecsum_normal_loop pass %d failed "
- "with error %d\n", pass, ret);
- return ret;
- }
- hdfsSeek(ldata->fs, ldata->file, 0);
- }
- return 0;
-}
-
-static void vecsum_local(struct local_data *cdata, const struct options *opts)
-{
- int pass;
-
- for (pass = 0; pass < opts->passes; pass++) {
- double sum = vecsum(cdata->mmap, cdata->length / sizeof(double));
- printf("finished vecsum_local pass %d. sum = %g\n", pass, sum);
- }
-}
-
-static long long vecsum_length(const struct options *opts,
- const struct libhdfs_data *ldata)
-{
- if (opts->ty == VECSUM_LOCAL) {
- struct stat st_buf = { 0 };
- if (stat(opts->path, &st_buf)) {
- int err = errno;
- fprintf(stderr, "vecsum_length: stat(%s) failed: "
- "error %d (%s)\n", opts->path, err, strerror(err));
- return -EIO;
- }
- return st_buf.st_size;
- } else {
- return ldata->length;
- }
-}
-
-/*
- * vecsum is a microbenchmark which measures the speed of various ways of
- * reading from HDFS. It creates a file containing floating-point 'doubles',
- * and computes the sum of all the doubles several times. For some CPUs,
- * assembly optimizations are used for the summation (SSE, etc).
- */
-int main(void)
-{
- int ret = 1;
- struct options *opts = NULL;
- struct local_data *cdata = NULL;
- struct libhdfs_data *ldata = NULL;
- struct stopwatch *watch = NULL;
-
- if (check_byte_size(VECSUM_CHUNK_SIZE, "VECSUM_CHUNK_SIZE") ||
- check_byte_size(ZCR_READ_CHUNK_SIZE,
- "ZCR_READ_CHUNK_SIZE") ||
- check_byte_size(NORMAL_READ_CHUNK_SIZE,
- "NORMAL_READ_CHUNK_SIZE")) {
- goto done;
- }
- opts = options_create();
- if (!opts)
- goto done;
- if (opts->ty == VECSUM_LOCAL) {
- cdata = local_data_create(opts);
- if (!cdata)
- goto done;
- } else {
- ldata = libhdfs_data_create(opts);
- if (!ldata)
- goto done;
- }
- watch = stopwatch_create();
- if (!watch)
- goto done;
- switch (opts->ty) {
- case VECSUM_LOCAL:
- vecsum_local(cdata, opts);
- ret = 0;
- break;
- case VECSUM_LIBHDFS:
- ret = vecsum_libhdfs(ldata, opts);
- break;
- case VECSUM_ZCR:
- ret = vecsum_zcr(ldata, opts);
- break;
- }
- if (ret) {
- fprintf(stderr, "vecsum failed with error %d\n", ret);
- goto done;
- }
- ret = 0;
-done:
- fprintf(stderr, "cleaning up...\n");
- if (watch && (ret == 0)) {
- long long length = vecsum_length(opts, ldata);
- if (length >= 0) {
- stopwatch_stop(watch, length * opts->passes);
- }
- }
- if (cdata)
- local_data_free(cdata);
- if (ldata)
- libhdfs_data_free(ldata);
- if (opts)
- options_free(opts);
- return ret;
-}
-
-// vim: ts=4:sw=4:tw=79:et
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test_libhdfs_threaded.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test_libhdfs_threaded.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test_libhdfs_threaded.c
deleted file mode 100644
index 702430c..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test_libhdfs_threaded.c
+++ /dev/null
@@ -1,360 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "expect.h"
-#include "hdfs.h"
-#include "native_mini_dfs.h"
-#include "os/thread.h"
-
-#include <errno.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define TO_STR_HELPER(X) #X
-#define TO_STR(X) TO_STR_HELPER(X)
-
-#define TLH_MAX_THREADS 100
-
-#define TLH_DEFAULT_BLOCK_SIZE 134217728
-
-static struct NativeMiniDfsCluster* tlhCluster;
-
-struct tlhThreadInfo {
- /** Thread index */
- int threadIdx;
- /** 0 = thread was successful; error code otherwise */
- int success;
- /** thread identifier */
- thread theThread;
-};
-
-static int hdfsSingleNameNodeConnect(struct NativeMiniDfsCluster *cl, hdfsFS *fs,
- const char *username)
-{
- int ret;
- tPort port;
- hdfsFS hdfs;
- struct hdfsBuilder *bld;
-
- port = (tPort)nmdGetNameNodePort(cl);
- if (port < 0) {
- fprintf(stderr, "hdfsSingleNameNodeConnect: nmdGetNameNodePort "
- "returned error %d\n", port);
- return port;
- }
- bld = hdfsNewBuilder();
- if (!bld)
- return -ENOMEM;
- hdfsBuilderSetForceNewInstance(bld);
- hdfsBuilderSetNameNode(bld, "localhost");
- hdfsBuilderSetNameNodePort(bld, port);
- hdfsBuilderConfSetStr(bld, "dfs.block.size",
- TO_STR(TLH_DEFAULT_BLOCK_SIZE));
- hdfsBuilderConfSetStr(bld, "dfs.blocksize",
- TO_STR(TLH_DEFAULT_BLOCK_SIZE));
- if (username) {
- hdfsBuilderSetUserName(bld, username);
- }
- hdfs = hdfsBuilderConnect(bld);
- if (!hdfs) {
- ret = -errno;
- return ret;
- }
- *fs = hdfs;
- return 0;
-}
-
-static int doTestGetDefaultBlockSize(hdfsFS fs, const char *path)
-{
- int64_t blockSize;
- int ret;
-
- blockSize = hdfsGetDefaultBlockSize(fs);
- if (blockSize < 0) {
- ret = errno;
- fprintf(stderr, "hdfsGetDefaultBlockSize failed with error %d\n", ret);
- return ret;
- } else if (blockSize != TLH_DEFAULT_BLOCK_SIZE) {
- fprintf(stderr, "hdfsGetDefaultBlockSize got %"PRId64", but we "
- "expected %d\n", blockSize, TLH_DEFAULT_BLOCK_SIZE);
- return EIO;
- }
-
- blockSize = hdfsGetDefaultBlockSizeAtPath(fs, path);
- if (blockSize < 0) {
- ret = errno;
- fprintf(stderr, "hdfsGetDefaultBlockSizeAtPath(%s) failed with "
- "error %d\n", path, ret);
- return ret;
- } else if (blockSize != TLH_DEFAULT_BLOCK_SIZE) {
- fprintf(stderr, "hdfsGetDefaultBlockSizeAtPath(%s) got "
- "%"PRId64", but we expected %d\n",
- path, blockSize, TLH_DEFAULT_BLOCK_SIZE);
- return EIO;
- }
- return 0;
-}
-
-struct tlhPaths {
- char prefix[256];
- char file1[256];
- char file2[256];
-};
-
-static int setupPaths(const struct tlhThreadInfo *ti, struct tlhPaths *paths)
-{
- memset(paths, 0, sizeof(*paths));
- if (snprintf(paths->prefix, sizeof(paths->prefix), "/tlhData%04d",
- ti->threadIdx) >= sizeof(paths->prefix)) {
- return ENAMETOOLONG;
- }
- if (snprintf(paths->file1, sizeof(paths->file1), "%s/file1",
- paths->prefix) >= sizeof(paths->file1)) {
- return ENAMETOOLONG;
- }
- if (snprintf(paths->file2, sizeof(paths->file2), "%s/file2",
- paths->prefix) >= sizeof(paths->file2)) {
- return ENAMETOOLONG;
- }
- return 0;
-}
-
-static int doTestHdfsOperations(struct tlhThreadInfo *ti, hdfsFS fs,
- const struct tlhPaths *paths)
-{
- char tmp[4096];
- hdfsFile file;
- int ret, expected, numEntries;
- hdfsFileInfo *fileInfo;
- struct hdfsReadStatistics *readStats = NULL;
-
- if (hdfsExists(fs, paths->prefix) == 0) {
- EXPECT_ZERO(hdfsDelete(fs, paths->prefix, 1));
- }
- EXPECT_ZERO(hdfsCreateDirectory(fs, paths->prefix));
-
- EXPECT_ZERO(doTestGetDefaultBlockSize(fs, paths->prefix));
-
- /* There should be no entry in the directory. */
- errno = EACCES; // see if errno is set to 0 on success
- EXPECT_NULL_WITH_ERRNO(hdfsListDirectory(fs, paths->prefix, &numEntries), 0);
- if (numEntries != 0) {
- fprintf(stderr, "hdfsListDirectory set numEntries to "
- "%d on empty directory.", numEntries);
- }
-
- /* There should not be any file to open for reading. */
- EXPECT_NULL(hdfsOpenFile(fs, paths->file1, O_RDONLY, 0, 0, 0));
-
- /* hdfsOpenFile should not accept mode = 3 */
- EXPECT_NULL(hdfsOpenFile(fs, paths->file1, 3, 0, 0, 0));
-
- file = hdfsOpenFile(fs, paths->file1, O_WRONLY, 0, 0, 0);
- EXPECT_NONNULL(file);
-
- /* TODO: implement writeFully and use it here */
- expected = (int)strlen(paths->prefix);
- ret = hdfsWrite(fs, file, paths->prefix, expected);
- if (ret < 0) {
- ret = errno;
- fprintf(stderr, "hdfsWrite failed and set errno %d\n", ret);
- return ret;
- }
- if (ret != expected) {
- fprintf(stderr, "hdfsWrite was supposed to write %d bytes, but "
- "it wrote %d\n", ret, expected);
- return EIO;
- }
- EXPECT_ZERO(hdfsFlush(fs, file));
- EXPECT_ZERO(hdfsHSync(fs, file));
- EXPECT_ZERO(hdfsCloseFile(fs, file));
-
- /* There should be 1 entry in the directory. */
- EXPECT_NONNULL(hdfsListDirectory(fs, paths->prefix, &numEntries));
- if (numEntries != 1) {
- fprintf(stderr, "hdfsListDirectory set numEntries to "
- "%d on directory containing 1 file.", numEntries);
- }
-
- /* Let's re-open the file for reading */
- file = hdfsOpenFile(fs, paths->file1, O_RDONLY, 0, 0, 0);
- EXPECT_NONNULL(file);
-
- EXPECT_ZERO(hdfsFileGetReadStatistics(file, &readStats));
- errno = 0;
- EXPECT_UINT64_EQ(UINT64_C(0), readStats->totalBytesRead);
- EXPECT_UINT64_EQ(UINT64_C(0), readStats->totalLocalBytesRead);
- EXPECT_UINT64_EQ(UINT64_C(0), readStats->totalShortCircuitBytesRead);
- hdfsFileFreeReadStatistics(readStats);
- /* TODO: implement readFully and use it here */
- ret = hdfsRead(fs, file, tmp, sizeof(tmp));
- if (ret < 0) {
- ret = errno;
- fprintf(stderr, "hdfsRead failed and set errno %d\n", ret);
- return ret;
- }
- if (ret != expected) {
- fprintf(stderr, "hdfsRead was supposed to read %d bytes, but "
- "it read %d\n", ret, expected);
- return EIO;
- }
- EXPECT_ZERO(hdfsFileGetReadStatistics(file, &readStats));
- errno = 0;
- EXPECT_UINT64_EQ((uint64_t)expected, readStats->totalBytesRead);
- hdfsFileFreeReadStatistics(readStats);
- EXPECT_ZERO(hdfsFileClearReadStatistics(file));
- EXPECT_ZERO(hdfsFileGetReadStatistics(file, &readStats));
- EXPECT_UINT64_EQ((uint64_t)0, readStats->totalBytesRead);
- hdfsFileFreeReadStatistics(readStats);
- EXPECT_ZERO(memcmp(paths->prefix, tmp, expected));
- EXPECT_ZERO(hdfsCloseFile(fs, file));
-
- // TODO: Non-recursive delete should fail?
- //EXPECT_NONZERO(hdfsDelete(fs, prefix, 0));
- EXPECT_ZERO(hdfsCopy(fs, paths->file1, fs, paths->file2));
-
- EXPECT_ZERO(hdfsChown(fs, paths->file2, NULL, NULL));
- EXPECT_ZERO(hdfsChown(fs, paths->file2, NULL, "doop"));
- fileInfo = hdfsGetPathInfo(fs, paths->file2);
- EXPECT_NONNULL(fileInfo);
- EXPECT_ZERO(strcmp("doop", fileInfo->mGroup));
- EXPECT_ZERO(hdfsFileIsEncrypted(fileInfo));
- hdfsFreeFileInfo(fileInfo, 1);
-
- EXPECT_ZERO(hdfsChown(fs, paths->file2, "ha", "doop2"));
- fileInfo = hdfsGetPathInfo(fs, paths->file2);
- EXPECT_NONNULL(fileInfo);
- EXPECT_ZERO(strcmp("ha", fileInfo->mOwner));
- EXPECT_ZERO(strcmp("doop2", fileInfo->mGroup));
- hdfsFreeFileInfo(fileInfo, 1);
-
- EXPECT_ZERO(hdfsChown(fs, paths->file2, "ha2", NULL));
- fileInfo = hdfsGetPathInfo(fs, paths->file2);
- EXPECT_NONNULL(fileInfo);
- EXPECT_ZERO(strcmp("ha2", fileInfo->mOwner));
- EXPECT_ZERO(strcmp("doop2", fileInfo->mGroup));
- hdfsFreeFileInfo(fileInfo, 1);
-
- snprintf(tmp, sizeof(tmp), "%s/nonexistent-file-name", paths->prefix);
- EXPECT_NEGATIVE_ONE_WITH_ERRNO(hdfsChown(fs, tmp, "ha3", NULL), ENOENT);
- return 0;
-}
-
-static int testHdfsOperationsImpl(struct tlhThreadInfo *ti)
-{
- hdfsFS fs = NULL;
- struct tlhPaths paths;
-
- fprintf(stderr, "testHdfsOperations(threadIdx=%d): starting\n",
- ti->threadIdx);
- EXPECT_ZERO(hdfsSingleNameNodeConnect(tlhCluster, &fs, NULL));
- EXPECT_ZERO(setupPaths(ti, &paths));
- // test some operations
- EXPECT_ZERO(doTestHdfsOperations(ti, fs, &paths));
- EXPECT_ZERO(hdfsDisconnect(fs));
- // reconnect as user "foo" and verify that we get permission errors
- EXPECT_ZERO(hdfsSingleNameNodeConnect(tlhCluster, &fs, "foo"));
- EXPECT_NEGATIVE_ONE_WITH_ERRNO(hdfsChown(fs, paths.file1, "ha3", NULL), EACCES);
- EXPECT_ZERO(hdfsDisconnect(fs));
- // reconnect to do the final delete.
- EXPECT_ZERO(hdfsSingleNameNodeConnect(tlhCluster, &fs, NULL));
- EXPECT_ZERO(hdfsDelete(fs, paths.prefix, 1));
- EXPECT_ZERO(hdfsDisconnect(fs));
- return 0;
-}
-
-static void testHdfsOperations(void *v)
-{
- struct tlhThreadInfo *ti = (struct tlhThreadInfo*)v;
- int ret = testHdfsOperationsImpl(ti);
- ti->success = ret;
-}
-
-static int checkFailures(struct tlhThreadInfo *ti, int tlhNumThreads)
-{
- int i, threadsFailed = 0;
- const char *sep = "";
-
- for (i = 0; i < tlhNumThreads; i++) {
- if (ti[i].success != 0) {
- threadsFailed = 1;
- }
- }
- if (!threadsFailed) {
- fprintf(stderr, "testLibHdfs: all threads succeeded. SUCCESS.\n");
- return EXIT_SUCCESS;
- }
- fprintf(stderr, "testLibHdfs: some threads failed: [");
- for (i = 0; i < tlhNumThreads; i++) {
- if (ti[i].success != 0) {
- fprintf(stderr, "%s%d", sep, i);
- sep = ", ";
- }
- }
- fprintf(stderr, "]. FAILURE.\n");
- return EXIT_FAILURE;
-}
-
-/**
- * Test that we can write a file with libhdfs and then read it back
- */
-int main(void)
-{
- int i, tlhNumThreads;
- const char *tlhNumThreadsStr;
- struct tlhThreadInfo ti[TLH_MAX_THREADS];
- struct NativeMiniDfsConf conf = {
- 1, /* doFormat */
- };
-
- tlhNumThreadsStr = getenv("TLH_NUM_THREADS");
- if (!tlhNumThreadsStr) {
- tlhNumThreadsStr = "3";
- }
- tlhNumThreads = atoi(tlhNumThreadsStr);
- if ((tlhNumThreads <= 0) || (tlhNumThreads > TLH_MAX_THREADS)) {
- fprintf(stderr, "testLibHdfs: must have a number of threads "
- "between 1 and %d inclusive, not %d\n",
- TLH_MAX_THREADS, tlhNumThreads);
- return EXIT_FAILURE;
- }
- memset(&ti[0], 0, sizeof(ti));
- for (i = 0; i < tlhNumThreads; i++) {
- ti[i].threadIdx = i;
- }
-
- tlhCluster = nmdCreate(&conf);
- EXPECT_NONNULL(tlhCluster);
- EXPECT_ZERO(nmdWaitClusterUp(tlhCluster));
-
- for (i = 0; i < tlhNumThreads; i++) {
- ti[i].theThread.start = testHdfsOperations;
- ti[i].theThread.arg = &ti[i];
- EXPECT_ZERO(threadCreate(&ti[i].theThread));
- }
- for (i = 0; i < tlhNumThreads; i++) {
- EXPECT_ZERO(threadJoin(&ti[i].theThread));
- }
-
- EXPECT_ZERO(nmdShutdown(tlhCluster));
- nmdFree(tlhCluster);
- return checkFailures(ti, tlhNumThreads);
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test_native_mini_dfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test_native_mini_dfs.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test_native_mini_dfs.c
deleted file mode 100644
index 850b0fc..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test_native_mini_dfs.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "expect.h"
-#include "native_mini_dfs.h"
-
-#include <errno.h>
-
-static struct NativeMiniDfsConf conf = {
- 1, /* doFormat */
-};
-
-/**
- * Test that we can create a MiniDFSCluster and shut it down.
- */
-int main(void) {
- struct NativeMiniDfsCluster* cl;
-
- cl = nmdCreate(&conf);
- EXPECT_NONNULL(cl);
- EXPECT_ZERO(nmdWaitClusterUp(cl));
- EXPECT_ZERO(nmdShutdown(cl));
- nmdFree(cl);
-
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/posix_util.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/posix_util.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/posix_util.c
deleted file mode 100644
index 59308a5..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/posix_util.c
+++ /dev/null
@@ -1,155 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "util/posix_util.h"
-
-#include <dirent.h>
-#include <errno.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <limits.h>
-
-static pthread_mutex_t gTempdirLock = PTHREAD_MUTEX_INITIALIZER;
-
-static int gTempdirNonce = 0;
-
-int recursiveDeleteContents(const char *path)
-{
- int ret;
- DIR *dp;
- struct dirent *de;
- char tmp[PATH_MAX];
-
- dp = opendir(path);
- if (!dp) {
- ret = -errno;
- fprintf(stderr, "recursiveDelete(%s) failed with error %d\n", path, ret);
- return ret;
- }
- while (1) {
- de = readdir(dp);
- if (!de) {
- ret = 0;
- break;
- }
- if ((de->d_name[0] == '.') && (de->d_name[1] == '\0'))
- continue;
- if ((de->d_name[0] == '.') && (de->d_name[1] == '.') &&
- (de->d_name[2] == '\0'))
- continue;
- snprintf(tmp, sizeof(tmp), "%s/%s", path, de->d_name);
- ret = recursiveDelete(tmp);
- if (ret)
- break;
- }
- if (closedir(dp)) {
- ret = -errno;
- fprintf(stderr, "recursiveDelete(%s): closedir failed with "
- "error %d\n", path, ret);
- return ret;
- }
- return ret;
-}
-
-/*
- * Simple recursive delete implementation.
- * It could be optimized, but there is no need at the moment.
- * TODO: use fstat, etc.
- */
-int recursiveDelete(const char *path)
-{
- int ret;
- struct stat stBuf;
-
- ret = stat(path, &stBuf);
- if (ret != 0) {
- ret = -errno;
- fprintf(stderr, "recursiveDelete(%s): stat failed with "
- "error %d\n", path, ret);
- return ret;
- }
- if (S_ISDIR(stBuf.st_mode)) {
- ret = recursiveDeleteContents(path);
- if (ret)
- return ret;
- ret = rmdir(path);
- if (ret) {
- ret = errno;
- fprintf(stderr, "recursiveDelete(%s): rmdir failed with error %d\n",
- path, ret);
- return ret;
- }
- } else {
- ret = unlink(path);
- if (ret) {
- ret = -errno;
- fprintf(stderr, "recursiveDelete(%s): unlink failed with "
- "error %d\n", path, ret);
- return ret;
- }
- }
- return 0;
-}
-
-int createTempDir(char *tempDir, int nameMax, int mode)
-{
- char tmp[PATH_MAX];
- int pid, nonce;
- const char *base = getenv("TMPDIR");
- if (!base)
- base = "/tmp";
- if (base[0] != '/') {
- // canonicalize non-absolute TMPDIR
- if (realpath(base, tmp) == NULL) {
- return -errno;
- }
- base = tmp;
- }
- pid = getpid();
- pthread_mutex_lock(&gTempdirLock);
- nonce = gTempdirNonce++;
- pthread_mutex_unlock(&gTempdirLock);
- snprintf(tempDir, nameMax, "%s/temp.%08d.%08d", base, pid, nonce);
- if (mkdir(tempDir, mode) == -1) {
- int ret = errno;
- return -ret;
- }
- return 0;
-}
-
-void sleepNoSig(int sec)
-{
- int ret;
- struct timespec req, rem;
-
- rem.tv_sec = sec;
- rem.tv_nsec = 0;
- do {
- req = rem;
- ret = nanosleep(&req, &rem);
- } while ((ret == -1) && (errno == EINTR));
- if (ret == -1) {
- ret = errno;
- fprintf(stderr, "nanosleep error %d (%s)\n", ret, strerror(ret));
- }
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/posix_util.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/posix_util.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/posix_util.h
deleted file mode 100644
index c184c26..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/posix_util.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __POSIX_UTIL_H__
-#define __POSIX_UTIL_H__
-
-/**
- * Recursively delete the contents of a directory
- *
- * @param path directory whose contents we should delete
- *
- * @return 0 on success; error code otherwise
- */
-int recursiveDeleteContents(const char *path);
-
-/**
- * Recursively delete a local path, using unlink or rmdir as appropriate.
- *
- * @param path path to delete
- *
- * @return 0 on success; error code otherwise
- */
-int recursiveDelete(const char *path);
-
-/**
- * Get a temporary directory
- *
- * @param tempDir (out param) path to the temporary directory
- * @param nameMax Length of the tempDir buffer
- * @param mode Mode to create with
- *
- * @return 0 on success; error code otherwise
- */
-int createTempDir(char *tempDir, int nameMax, int mode);
-
-/**
- * Sleep without using signals
- *
- * @param sec Number of seconds to sleep
- */
-void sleepNoSig(int sec);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/tree.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/tree.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/tree.h
deleted file mode 100644
index ac78ee3..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/util/tree.h
+++ /dev/null
@@ -1,765 +0,0 @@
-/* $NetBSD: tree.h,v 1.8 2004/03/28 19:38:30 provos Exp $ */
-/* $OpenBSD: tree.h,v 1.7 2002/10/17 21:51:54 art Exp $ */
-/* $FreeBSD: src/sys/sys/tree.h,v 1.9.4.1 2011/09/23 00:51:37 kensmith Exp $ */
-
-/*-
- * Copyright 2002 Niels Provos <pr...@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef _SYS_TREE_H_
-#define _SYS_TREE_H_
-
-#include <sys/cdefs.h>
-
-/*
- * This file defines data structures for different types of trees:
- * splay trees and red-black trees.
- *
- * A splay tree is a self-organizing data structure. Every operation
- * on the tree causes a splay to happen. The splay moves the requested
- * node to the root of the tree and partly rebalances it.
- *
- * This has the benefit that request locality causes faster lookups as
- * the requested nodes move to the top of the tree. On the other hand,
- * every lookup causes memory writes.
- *
- * The Balance Theorem bounds the total access time for m operations
- * and n inserts on an initially empty tree as O((m + n)lg n). The
- * amortized cost for a sequence of m accesses to a splay tree is O(lg n);
- *
- * A red-black tree is a binary search tree with the node color as an
- * extra attribute. It fulfills a set of conditions:
- * - every search path from the root to a leaf consists of the
- * same number of black nodes,
- * - each red node (except for the root) has a black parent,
- * - each leaf node is black.
- *
- * Every operation on a red-black tree is bounded as O(lg n).
- * The maximum height of a red-black tree is 2lg (n+1).
- */
-
-#define SPLAY_HEAD(name, type) \
-struct name { \
- struct type *sph_root; /* root of the tree */ \
-}
-
-#define SPLAY_INITIALIZER(root) \
- { NULL }
-
-#define SPLAY_INIT(root) do { \
- (root)->sph_root = NULL; \
-} while (/*CONSTCOND*/ 0)
-
-#define SPLAY_ENTRY(type) \
-struct { \
- struct type *spe_left; /* left element */ \
- struct type *spe_right; /* right element */ \
-}
-
-#define SPLAY_LEFT(elm, field) (elm)->field.spe_left
-#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right
-#define SPLAY_ROOT(head) (head)->sph_root
-#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL)
-
-/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
-#define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \
- SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \
- SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
- (head)->sph_root = tmp; \
-} while (/*CONSTCOND*/ 0)
-
-#define SPLAY_ROTATE_LEFT(head, tmp, field) do { \
- SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \
- SPLAY_LEFT(tmp, field) = (head)->sph_root; \
- (head)->sph_root = tmp; \
-} while (/*CONSTCOND*/ 0)
-
-#define SPLAY_LINKLEFT(head, tmp, field) do { \
- SPLAY_LEFT(tmp, field) = (head)->sph_root; \
- tmp = (head)->sph_root; \
- (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \
-} while (/*CONSTCOND*/ 0)
-
-#define SPLAY_LINKRIGHT(head, tmp, field) do { \
- SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
- tmp = (head)->sph_root; \
- (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \
-} while (/*CONSTCOND*/ 0)
-
-#define SPLAY_ASSEMBLE(head, node, left, right, field) do { \
- SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \
- SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\
- SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \
- SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \
-} while (/*CONSTCOND*/ 0)
-
-/* Generates prototypes and inline functions */
-
-#define SPLAY_PROTOTYPE(name, type, field, cmp) \
-void name##_SPLAY(struct name *, struct type *); \
-void name##_SPLAY_MINMAX(struct name *, int); \
-struct type *name##_SPLAY_INSERT(struct name *, struct type *); \
-struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \
- \
-/* Finds the node with the same key as elm */ \
-static __inline struct type * \
-name##_SPLAY_FIND(struct name *head, struct type *elm) \
-{ \
- if (SPLAY_EMPTY(head)) \
- return(NULL); \
- name##_SPLAY(head, elm); \
- if ((cmp)(elm, (head)->sph_root) == 0) \
- return (head->sph_root); \
- return (NULL); \
-} \
- \
-static __inline struct type * \
-name##_SPLAY_NEXT(struct name *head, struct type *elm) \
-{ \
- name##_SPLAY(head, elm); \
- if (SPLAY_RIGHT(elm, field) != NULL) { \
- elm = SPLAY_RIGHT(elm, field); \
- while (SPLAY_LEFT(elm, field) != NULL) { \
- elm = SPLAY_LEFT(elm, field); \
- } \
- } else \
- elm = NULL; \
- return (elm); \
-} \
- \
-static __inline struct type * \
-name##_SPLAY_MIN_MAX(struct name *head, int val) \
-{ \
- name##_SPLAY_MINMAX(head, val); \
- return (SPLAY_ROOT(head)); \
-}
-
-/* Main splay operation.
- * Moves node close to the key of elm to top
- */
-#define SPLAY_GENERATE(name, type, field, cmp) \
-struct type * \
-name##_SPLAY_INSERT(struct name *head, struct type *elm) \
-{ \
- if (SPLAY_EMPTY(head)) { \
- SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \
- } else { \
- int __comp; \
- name##_SPLAY(head, elm); \
- __comp = (cmp)(elm, (head)->sph_root); \
- if(__comp < 0) { \
- SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\
- SPLAY_RIGHT(elm, field) = (head)->sph_root; \
- SPLAY_LEFT((head)->sph_root, field) = NULL; \
- } else if (__comp > 0) { \
- SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\
- SPLAY_LEFT(elm, field) = (head)->sph_root; \
- SPLAY_RIGHT((head)->sph_root, field) = NULL; \
- } else \
- return ((head)->sph_root); \
- } \
- (head)->sph_root = (elm); \
- return (NULL); \
-} \
- \
-struct type * \
-name##_SPLAY_REMOVE(struct name *head, struct type *elm) \
-{ \
- struct type *__tmp; \
- if (SPLAY_EMPTY(head)) \
- return (NULL); \
- name##_SPLAY(head, elm); \
- if ((cmp)(elm, (head)->sph_root) == 0) { \
- if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \
- (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\
- } else { \
- __tmp = SPLAY_RIGHT((head)->sph_root, field); \
- (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\
- name##_SPLAY(head, elm); \
- SPLAY_RIGHT((head)->sph_root, field) = __tmp; \
- } \
- return (elm); \
- } \
- return (NULL); \
-} \
- \
-void \
-name##_SPLAY(struct name *head, struct type *elm) \
-{ \
- struct type __node, *__left, *__right, *__tmp; \
- int __comp; \
-\
- SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
- __left = __right = &__node; \
-\
- while ((__comp = (cmp)(elm, (head)->sph_root)) != 0) { \
- if (__comp < 0) { \
- __tmp = SPLAY_LEFT((head)->sph_root, field); \
- if (__tmp == NULL) \
- break; \
- if ((cmp)(elm, __tmp) < 0){ \
- SPLAY_ROTATE_RIGHT(head, __tmp, field); \
- if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
- break; \
- } \
- SPLAY_LINKLEFT(head, __right, field); \
- } else if (__comp > 0) { \
- __tmp = SPLAY_RIGHT((head)->sph_root, field); \
- if (__tmp == NULL) \
- break; \
- if ((cmp)(elm, __tmp) > 0){ \
- SPLAY_ROTATE_LEFT(head, __tmp, field); \
- if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
- break; \
- } \
- SPLAY_LINKRIGHT(head, __left, field); \
- } \
- } \
- SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
-} \
- \
-/* Splay with either the minimum or the maximum element \
- * Used to find minimum or maximum element in tree. \
- */ \
-void name##_SPLAY_MINMAX(struct name *head, int __comp) \
-{ \
- struct type __node, *__left, *__right, *__tmp; \
-\
- SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
- __left = __right = &__node; \
-\
- while (1) { \
- if (__comp < 0) { \
- __tmp = SPLAY_LEFT((head)->sph_root, field); \
- if (__tmp == NULL) \
- break; \
- if (__comp < 0){ \
- SPLAY_ROTATE_RIGHT(head, __tmp, field); \
- if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
- break; \
- } \
- SPLAY_LINKLEFT(head, __right, field); \
- } else if (__comp > 0) { \
- __tmp = SPLAY_RIGHT((head)->sph_root, field); \
- if (__tmp == NULL) \
- break; \
- if (__comp > 0) { \
- SPLAY_ROTATE_LEFT(head, __tmp, field); \
- if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
- break; \
- } \
- SPLAY_LINKRIGHT(head, __left, field); \
- } \
- } \
- SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
-}
-
-#define SPLAY_NEGINF -1
-#define SPLAY_INF 1
-
-#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y)
-#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y)
-#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y)
-#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y)
-#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \
- : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
-#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \
- : name##_SPLAY_MIN_MAX(x, SPLAY_INF))
-
-#define SPLAY_FOREACH(x, name, head) \
- for ((x) = SPLAY_MIN(name, head); \
- (x) != NULL; \
- (x) = SPLAY_NEXT(name, head, x))
-
-/* Macros that define a red-black tree */
-#define RB_HEAD(name, type) \
-struct name { \
- struct type *rbh_root; /* root of the tree */ \
-}
-
-#define RB_INITIALIZER(root) \
- { NULL }
-
-#define RB_INIT(root) do { \
- (root)->rbh_root = NULL; \
-} while (/*CONSTCOND*/ 0)
-
-#define RB_BLACK 0
-#define RB_RED 1
-#define RB_ENTRY(type) \
-struct { \
- struct type *rbe_left; /* left element */ \
- struct type *rbe_right; /* right element */ \
- struct type *rbe_parent; /* parent element */ \
- int rbe_color; /* node color */ \
-}
-
-#define RB_LEFT(elm, field) (elm)->field.rbe_left
-#define RB_RIGHT(elm, field) (elm)->field.rbe_right
-#define RB_PARENT(elm, field) (elm)->field.rbe_parent
-#define RB_COLOR(elm, field) (elm)->field.rbe_color
-#define RB_ROOT(head) (head)->rbh_root
-#define RB_EMPTY(head) (RB_ROOT(head) == NULL)
-
-#define RB_SET(elm, parent, field) do { \
- RB_PARENT(elm, field) = parent; \
- RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \
- RB_COLOR(elm, field) = RB_RED; \
-} while (/*CONSTCOND*/ 0)
-
-#define RB_SET_BLACKRED(black, red, field) do { \
- RB_COLOR(black, field) = RB_BLACK; \
- RB_COLOR(red, field) = RB_RED; \
-} while (/*CONSTCOND*/ 0)
-
-#ifndef RB_AUGMENT
-#define RB_AUGMENT(x) do {} while (0)
-#endif
-
-#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \
- (tmp) = RB_RIGHT(elm, field); \
- if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field)) != NULL) { \
- RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \
- } \
- RB_AUGMENT(elm); \
- if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
- if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
- RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
- else \
- RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
- } else \
- (head)->rbh_root = (tmp); \
- RB_LEFT(tmp, field) = (elm); \
- RB_PARENT(elm, field) = (tmp); \
- RB_AUGMENT(tmp); \
- if ((RB_PARENT(tmp, field))) \
- RB_AUGMENT(RB_PARENT(tmp, field)); \
-} while (/*CONSTCOND*/ 0)
-
-#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \
- (tmp) = RB_LEFT(elm, field); \
- if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field)) != NULL) { \
- RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \
- } \
- RB_AUGMENT(elm); \
- if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
- if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
- RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
- else \
- RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
- } else \
- (head)->rbh_root = (tmp); \
- RB_RIGHT(tmp, field) = (elm); \
- RB_PARENT(elm, field) = (tmp); \
- RB_AUGMENT(tmp); \
- if ((RB_PARENT(tmp, field))) \
- RB_AUGMENT(RB_PARENT(tmp, field)); \
-} while (/*CONSTCOND*/ 0)
-
-/* Generates prototypes and inline functions */
-#define RB_PROTOTYPE(name, type, field, cmp) \
- RB_PROTOTYPE_INTERNAL(name, type, field, cmp,)
-#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \
- RB_PROTOTYPE_INTERNAL(name, type, field, cmp, __unused static)
-#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \
-attr void name##_RB_INSERT_COLOR(struct name *, struct type *); \
-attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
-attr struct type *name##_RB_REMOVE(struct name *, struct type *); \
-attr struct type *name##_RB_INSERT(struct name *, struct type *); \
-attr struct type *name##_RB_FIND(struct name *, struct type *); \
-attr struct type *name##_RB_NFIND(struct name *, struct type *); \
-attr struct type *name##_RB_NEXT(struct type *); \
-attr struct type *name##_RB_PREV(struct type *); \
-attr struct type *name##_RB_MINMAX(struct name *, int); \
- \
-
-/* Main rb operation.
- * Moves node close to the key of elm to top
- */
-#define RB_GENERATE(name, type, field, cmp) \
- RB_GENERATE_INTERNAL(name, type, field, cmp,)
-#define RB_GENERATE_STATIC(name, type, field, cmp) \
- RB_GENERATE_INTERNAL(name, type, field, cmp, __unused static)
-#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \
-attr void \
-name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \
-{ \
- struct type *parent, *gparent, *tmp; \
- while ((parent = RB_PARENT(elm, field)) != NULL && \
- RB_COLOR(parent, field) == RB_RED) { \
- gparent = RB_PARENT(parent, field); \
- if (parent == RB_LEFT(gparent, field)) { \
- tmp = RB_RIGHT(gparent, field); \
- if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
- RB_COLOR(tmp, field) = RB_BLACK; \
- RB_SET_BLACKRED(parent, gparent, field);\
- elm = gparent; \
- continue; \
- } \
- if (RB_RIGHT(parent, field) == elm) { \
- RB_ROTATE_LEFT(head, parent, tmp, field);\
- tmp = parent; \
- parent = elm; \
- elm = tmp; \
- } \
- RB_SET_BLACKRED(parent, gparent, field); \
- RB_ROTATE_RIGHT(head, gparent, tmp, field); \
- } else { \
- tmp = RB_LEFT(gparent, field); \
- if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
- RB_COLOR(tmp, field) = RB_BLACK; \
- RB_SET_BLACKRED(parent, gparent, field);\
- elm = gparent; \
- continue; \
- } \
- if (RB_LEFT(parent, field) == elm) { \
- RB_ROTATE_RIGHT(head, parent, tmp, field);\
- tmp = parent; \
- parent = elm; \
- elm = tmp; \
- } \
- RB_SET_BLACKRED(parent, gparent, field); \
- RB_ROTATE_LEFT(head, gparent, tmp, field); \
- } \
- } \
- RB_COLOR(head->rbh_root, field) = RB_BLACK; \
-} \
- \
-attr void \
-name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \
-{ \
- struct type *tmp; \
- while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \
- elm != RB_ROOT(head)) { \
- if (RB_LEFT(parent, field) == elm) { \
- tmp = RB_RIGHT(parent, field); \
- if (RB_COLOR(tmp, field) == RB_RED) { \
- RB_SET_BLACKRED(tmp, parent, field); \
- RB_ROTATE_LEFT(head, parent, tmp, field);\
- tmp = RB_RIGHT(parent, field); \
- } \
- if ((RB_LEFT(tmp, field) == NULL || \
- RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
- (RB_RIGHT(tmp, field) == NULL || \
- RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
- RB_COLOR(tmp, field) = RB_RED; \
- elm = parent; \
- parent = RB_PARENT(elm, field); \
- } else { \
- if (RB_RIGHT(tmp, field) == NULL || \
- RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\
- struct type *oleft; \
- if ((oleft = RB_LEFT(tmp, field)) \
- != NULL) \
- RB_COLOR(oleft, field) = RB_BLACK;\
- RB_COLOR(tmp, field) = RB_RED; \
- RB_ROTATE_RIGHT(head, tmp, oleft, field);\
- tmp = RB_RIGHT(parent, field); \
- } \
- RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
- RB_COLOR(parent, field) = RB_BLACK; \
- if (RB_RIGHT(tmp, field)) \
- RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\
- RB_ROTATE_LEFT(head, parent, tmp, field);\
- elm = RB_ROOT(head); \
- break; \
- } \
- } else { \
- tmp = RB_LEFT(parent, field); \
- if (RB_COLOR(tmp, field) == RB_RED) { \
- RB_SET_BLACKRED(tmp, parent, field); \
- RB_ROTATE_RIGHT(head, parent, tmp, field);\
- tmp = RB_LEFT(parent, field); \
- } \
- if ((RB_LEFT(tmp, field) == NULL || \
- RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
- (RB_RIGHT(tmp, field) == NULL || \
- RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
- RB_COLOR(tmp, field) = RB_RED; \
- elm = parent; \
- parent = RB_PARENT(elm, field); \
- } else { \
- if (RB_LEFT(tmp, field) == NULL || \
- RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\
- struct type *oright; \
- if ((oright = RB_RIGHT(tmp, field)) \
- != NULL) \
- RB_COLOR(oright, field) = RB_BLACK;\
- RB_COLOR(tmp, field) = RB_RED; \
- RB_ROTATE_LEFT(head, tmp, oright, field);\
- tmp = RB_LEFT(parent, field); \
- } \
- RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
- RB_COLOR(parent, field) = RB_BLACK; \
- if (RB_LEFT(tmp, field)) \
- RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\
- RB_ROTATE_RIGHT(head, parent, tmp, field);\
- elm = RB_ROOT(head); \
- break; \
- } \
- } \
- } \
- if (elm) \
- RB_COLOR(elm, field) = RB_BLACK; \
-} \
- \
-attr struct type * \
-name##_RB_REMOVE(struct name *head, struct type *elm) \
-{ \
- struct type *child, *parent, *old = elm; \
- int color; \
- if (RB_LEFT(elm, field) == NULL) \
- child = RB_RIGHT(elm, field); \
- else if (RB_RIGHT(elm, field) == NULL) \
- child = RB_LEFT(elm, field); \
- else { \
- struct type *left; \
- elm = RB_RIGHT(elm, field); \
- while ((left = RB_LEFT(elm, field)) != NULL) \
- elm = left; \
- child = RB_RIGHT(elm, field); \
- parent = RB_PARENT(elm, field); \
- color = RB_COLOR(elm, field); \
- if (child) \
- RB_PARENT(child, field) = parent; \
- if (parent) { \
- if (RB_LEFT(parent, field) == elm) \
- RB_LEFT(parent, field) = child; \
- else \
- RB_RIGHT(parent, field) = child; \
- RB_AUGMENT(parent); \
- } else \
- RB_ROOT(head) = child; \
- if (RB_PARENT(elm, field) == old) \
- parent = elm; \
- (elm)->field = (old)->field; \
- if (RB_PARENT(old, field)) { \
- if (RB_LEFT(RB_PARENT(old, field), field) == old)\
- RB_LEFT(RB_PARENT(old, field), field) = elm;\
- else \
- RB_RIGHT(RB_PARENT(old, field), field) = elm;\
- RB_AUGMENT(RB_PARENT(old, field)); \
- } else \
- RB_ROOT(head) = elm; \
- RB_PARENT(RB_LEFT(old, field), field) = elm; \
- if (RB_RIGHT(old, field)) \
- RB_PARENT(RB_RIGHT(old, field), field) = elm; \
- if (parent) { \
- left = parent; \
- do { \
- RB_AUGMENT(left); \
- } while ((left = RB_PARENT(left, field)) != NULL); \
- } \
- goto color; \
- } \
- parent = RB_PARENT(elm, field); \
- color = RB_COLOR(elm, field); \
- if (child) \
- RB_PARENT(child, field) = parent; \
- if (parent) { \
- if (RB_LEFT(parent, field) == elm) \
- RB_LEFT(parent, field) = child; \
- else \
- RB_RIGHT(parent, field) = child; \
- RB_AUGMENT(parent); \
- } else \
- RB_ROOT(head) = child; \
-color: \
- if (color == RB_BLACK) \
- name##_RB_REMOVE_COLOR(head, parent, child); \
- return (old); \
-} \
- \
-/* Inserts a node into the RB tree */ \
-attr struct type * \
-name##_RB_INSERT(struct name *head, struct type *elm) \
-{ \
- struct type *tmp; \
- struct type *parent = NULL; \
- int comp = 0; \
- tmp = RB_ROOT(head); \
- while (tmp) { \
- parent = tmp; \
- comp = (cmp)(elm, parent); \
- if (comp < 0) \
- tmp = RB_LEFT(tmp, field); \
- else if (comp > 0) \
- tmp = RB_RIGHT(tmp, field); \
- else \
- return (tmp); \
- } \
- RB_SET(elm, parent, field); \
- if (parent != NULL) { \
- if (comp < 0) \
- RB_LEFT(parent, field) = elm; \
- else \
- RB_RIGHT(parent, field) = elm; \
- RB_AUGMENT(parent); \
- } else \
- RB_ROOT(head) = elm; \
- name##_RB_INSERT_COLOR(head, elm); \
- return (NULL); \
-} \
- \
-/* Finds the node with the same key as elm */ \
-attr struct type * \
-name##_RB_FIND(struct name *head, struct type *elm) \
-{ \
- struct type *tmp = RB_ROOT(head); \
- int comp; \
- while (tmp) { \
- comp = cmp(elm, tmp); \
- if (comp < 0) \
- tmp = RB_LEFT(tmp, field); \
- else if (comp > 0) \
- tmp = RB_RIGHT(tmp, field); \
- else \
- return (tmp); \
- } \
- return (NULL); \
-} \
- \
-/* Finds the first node greater than or equal to the search key */ \
-attr struct type * \
-name##_RB_NFIND(struct name *head, struct type *elm) \
-{ \
- struct type *tmp = RB_ROOT(head); \
- struct type *res = NULL; \
- int comp; \
- while (tmp) { \
- comp = cmp(elm, tmp); \
- if (comp < 0) { \
- res = tmp; \
- tmp = RB_LEFT(tmp, field); \
- } \
- else if (comp > 0) \
- tmp = RB_RIGHT(tmp, field); \
- else \
- return (tmp); \
- } \
- return (res); \
-} \
- \
-/* ARGSUSED */ \
-attr struct type * \
-name##_RB_NEXT(struct type *elm) \
-{ \
- if (RB_RIGHT(elm, field)) { \
- elm = RB_RIGHT(elm, field); \
- while (RB_LEFT(elm, field)) \
- elm = RB_LEFT(elm, field); \
- } else { \
- if (RB_PARENT(elm, field) && \
- (elm == RB_LEFT(RB_PARENT(elm, field), field))) \
- elm = RB_PARENT(elm, field); \
- else { \
- while (RB_PARENT(elm, field) && \
- (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\
- elm = RB_PARENT(elm, field); \
- elm = RB_PARENT(elm, field); \
- } \
- } \
- return (elm); \
-} \
- \
-/* ARGSUSED */ \
-attr struct type * \
-name##_RB_PREV(struct type *elm) \
-{ \
- if (RB_LEFT(elm, field)) { \
- elm = RB_LEFT(elm, field); \
- while (RB_RIGHT(elm, field)) \
- elm = RB_RIGHT(elm, field); \
- } else { \
- if (RB_PARENT(elm, field) && \
- (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \
- elm = RB_PARENT(elm, field); \
- else { \
- while (RB_PARENT(elm, field) && \
- (elm == RB_LEFT(RB_PARENT(elm, field), field)))\
- elm = RB_PARENT(elm, field); \
- elm = RB_PARENT(elm, field); \
- } \
- } \
- return (elm); \
-} \
- \
-attr struct type * \
-name##_RB_MINMAX(struct name *head, int val) \
-{ \
- struct type *tmp = RB_ROOT(head); \
- struct type *parent = NULL; \
- while (tmp) { \
- parent = tmp; \
- if (val < 0) \
- tmp = RB_LEFT(tmp, field); \
- else \
- tmp = RB_RIGHT(tmp, field); \
- } \
- return (parent); \
-}
-
-#define RB_NEGINF -1
-#define RB_INF 1
-
-#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y)
-#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y)
-#define RB_FIND(name, x, y) name##_RB_FIND(x, y)
-#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y)
-#define RB_NEXT(name, x, y) name##_RB_NEXT(y)
-#define RB_PREV(name, x, y) name##_RB_PREV(y)
-#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF)
-#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF)
-
-#define RB_FOREACH(x, name, head) \
- for ((x) = RB_MIN(name, head); \
- (x) != NULL; \
- (x) = name##_RB_NEXT(x))
-
-#define RB_FOREACH_FROM(x, name, y) \
- for ((x) = (y); \
- ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \
- (x) = (y))
-
-#define RB_FOREACH_SAFE(x, name, head, y) \
- for ((x) = RB_MIN(name, head); \
- ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \
- (x) = (y))
-
-#define RB_FOREACH_REVERSE(x, name, head) \
- for ((x) = RB_MAX(name, head); \
- (x) != NULL; \
- (x) = name##_RB_PREV(x))
-
-#define RB_FOREACH_REVERSE_FROM(x, name, y) \
- for ((x) = (y); \
- ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \
- (x) = (y))
-
-#define RB_FOREACH_REVERSE_SAFE(x, name, head, y) \
- for ((x) = RB_MAX(name, head); \
- ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \
- (x) = (y))
-
-#endif /* _SYS_TREE_H_ */
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/pom.xml b/hadoop-hdfs-project/pom.xml
index 0a61c46..4d53edd 100644
--- a/hadoop-hdfs-project/pom.xml
+++ b/hadoop-hdfs-project/pom.xml
@@ -33,6 +33,7 @@ http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modules>
<module>hadoop-hdfs</module>
<module>hadoop-hdfs-client</module>
+ <module>hadoop-hdfs-native-client</module>
<module>hadoop-hdfs-httpfs</module>
<module>hadoop-hdfs/src/contrib/bkjournal</module>
<module>hadoop-hdfs-nfs</module>
[14/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_query.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_query.c b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_query.c
deleted file mode 100644
index b082c08..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_query.c
+++ /dev/null
@@ -1,402 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-#include "hdfs_http_query.h"
-#include <math.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <errno.h>
-
-#define PERM_STR_LEN 4 // "644" + one byte for NUL
-#define SHORT_STR_LEN 6 // 65535 + NUL
-#define LONG_STR_LEN 21 // 2^64-1 = 18446744073709551615 + NUL
-
-/**
- * Create query based on NameNode hostname,
- * NameNode port, path, operation and other parameters
- *
- * @param host NameNode hostName
- * @param nnPort Port of NameNode
- * @param path Absolute path for the corresponding file
- * @param op Operations
- * @param paraNum Number of remaining parameters
- * @param paraNames Names of remaining parameters
- * @param paraValues Values of remaining parameters
- * @param url Holding the created URL
- * @return 0 on success and non-zero value to indicate error
- */
-static int createQueryURL(const char *host, unsigned int nnPort,
- const char *path, const char *op, int paraNum,
- const char **paraNames, const char **paraValues,
- char **queryUrl)
-{
- size_t length = 0;
- int i = 0, offset = 0, ret = 0;
- char *url = NULL;
- const char *protocol = "http://";
- const char *prefix = "/webhdfs/v1";
-
- if (!paraNames || !paraValues) {
- return EINVAL;
- }
- length = strlen(protocol) + strlen(host) + strlen(":") +
- SHORT_STR_LEN + strlen(prefix) + strlen(path) +
- strlen ("?op=") + strlen(op);
- for (i = 0; i < paraNum; i++) {
- if (paraNames[i] && paraValues[i]) {
- length += 2 + strlen(paraNames[i]) + strlen(paraValues[i]);
- }
- }
- url = malloc(length); // The '\0' has already been included
- // when using SHORT_STR_LEN
- if (!url) {
- return ENOMEM;
- }
-
- offset = snprintf(url, length, "%s%s:%d%s%s?op=%s",
- protocol, host, nnPort, prefix, path, op);
- if (offset >= length || offset < 0) {
- ret = EIO;
- goto done;
- }
- for (i = 0; i < paraNum; i++) {
- if (!paraNames[i] || !paraValues[i] || paraNames[i][0] == '\0' ||
- paraValues[i][0] == '\0') {
- continue;
- }
- offset += snprintf(url + offset, length - offset,
- "&%s=%s", paraNames[i], paraValues[i]);
- if (offset >= length || offset < 0) {
- ret = EIO;
- goto done;
- }
- }
-done:
- if (ret) {
- free(url);
- return ret;
- }
- *queryUrl = url;
- return 0;
-}
-
-int createUrlForMKDIR(const char *host, int nnPort,
- const char *path, const char *user, char **url)
-{
- const char *userPara = "user.name";
- return createQueryURL(host, nnPort, path, "MKDIRS", 1,
- &userPara, &user, url);
-}
-
-int createUrlForGetFileStatus(const char *host, int nnPort, const char *path,
- const char *user, char **url)
-{
- const char *userPara = "user.name";
- return createQueryURL(host, nnPort, path, "GETFILESTATUS", 1,
- &userPara, &user, url);
-}
-
-int createUrlForLS(const char *host, int nnPort, const char *path,
- const char *user, char **url)
-{
- const char *userPara = "user.name";
- return createQueryURL(host, nnPort, path, "LISTSTATUS",
- 1, &userPara, &user, url);
-}
-
-int createUrlForNnAPPEND(const char *host, int nnPort, const char *path,
- const char *user, char **url)
-{
- const char *userPara = "user.name";
- return createQueryURL(host, nnPort, path, "APPEND",
- 1, &userPara, &user, url);
-}
-
-int createUrlForMKDIRwithMode(const char *host, int nnPort, const char *path,
- int mode, const char *user, char **url)
-{
- int strlength;
- char permission[PERM_STR_LEN];
- const char *paraNames[2], *paraValues[2];
-
- paraNames[0] = "permission";
- paraNames[1] = "user.name";
- memset(permission, 0, PERM_STR_LEN);
- strlength = snprintf(permission, PERM_STR_LEN, "%o", mode);
- if (strlength < 0 || strlength >= PERM_STR_LEN) {
- return EIO;
- }
- paraValues[0] = permission;
- paraValues[1] = user;
-
- return createQueryURL(host, nnPort, path, "MKDIRS", 2,
- paraNames, paraValues, url);
-}
-
-int createUrlForRENAME(const char *host, int nnPort, const char *srcpath,
- const char *destpath, const char *user, char **url)
-{
- const char *paraNames[2], *paraValues[2];
- paraNames[0] = "destination";
- paraNames[1] = "user.name";
- paraValues[0] = destpath;
- paraValues[1] = user;
-
- return createQueryURL(host, nnPort, srcpath,
- "RENAME", 2, paraNames, paraValues, url);
-}
-
-int createUrlForCHMOD(const char *host, int nnPort, const char *path,
- int mode, const char *user, char **url)
-{
- int strlength;
- char permission[PERM_STR_LEN];
- const char *paraNames[2], *paraValues[2];
-
- paraNames[0] = "permission";
- paraNames[1] = "user.name";
- memset(permission, 0, PERM_STR_LEN);
- strlength = snprintf(permission, PERM_STR_LEN, "%o", mode);
- if (strlength < 0 || strlength >= PERM_STR_LEN) {
- return EIO;
- }
- paraValues[0] = permission;
- paraValues[1] = user;
-
- return createQueryURL(host, nnPort, path, "SETPERMISSION",
- 2, paraNames, paraValues, url);
-}
-
-int createUrlForDELETE(const char *host, int nnPort, const char *path,
- int recursive, const char *user, char **url)
-{
- const char *paraNames[2], *paraValues[2];
- paraNames[0] = "recursive";
- paraNames[1] = "user.name";
- if (recursive) {
- paraValues[0] = "true";
- } else {
- paraValues[0] = "false";
- }
- paraValues[1] = user;
-
- return createQueryURL(host, nnPort, path, "DELETE",
- 2, paraNames, paraValues, url);
-}
-
-int createUrlForCHOWN(const char *host, int nnPort, const char *path,
- const char *owner, const char *group,
- const char *user, char **url)
-{
- const char *paraNames[3], *paraValues[3];
- paraNames[0] = "owner";
- paraNames[1] = "group";
- paraNames[2] = "user.name";
- paraValues[0] = owner;
- paraValues[1] = group;
- paraValues[2] = user;
-
- return createQueryURL(host, nnPort, path, "SETOWNER",
- 3, paraNames, paraValues, url);
-}
-
-int createUrlForOPEN(const char *host, int nnPort, const char *path,
- const char *user, size_t offset, size_t length, char **url)
-{
- int strlength;
- char offsetStr[LONG_STR_LEN], lengthStr[LONG_STR_LEN];
- const char *paraNames[3], *paraValues[3];
-
- paraNames[0] = "offset";
- paraNames[1] = "length";
- paraNames[2] = "user.name";
- memset(offsetStr, 0, LONG_STR_LEN);
- memset(lengthStr, 0, LONG_STR_LEN);
- strlength = snprintf(offsetStr, LONG_STR_LEN, "%lu", offset);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- strlength = snprintf(lengthStr, LONG_STR_LEN, "%lu", length);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- paraValues[0] = offsetStr;
- paraValues[1] = lengthStr;
- paraValues[2] = user;
-
- return createQueryURL(host, nnPort, path, "OPEN",
- 3, paraNames, paraValues, url);
-}
-
-int createUrlForUTIMES(const char *host, int nnPort, const char *path,
- long unsigned mTime, long unsigned aTime,
- const char *user, char **url)
-{
- int strlength;
- char modTime[LONG_STR_LEN], acsTime[LONG_STR_LEN];
- const char *paraNames[3], *paraValues[3];
-
- memset(modTime, 0, LONG_STR_LEN);
- memset(acsTime, 0, LONG_STR_LEN);
- strlength = snprintf(modTime, LONG_STR_LEN, "%lu", mTime);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- strlength = snprintf(acsTime, LONG_STR_LEN, "%lu", aTime);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- paraNames[0] = "modificationtime";
- paraNames[1] = "accesstime";
- paraNames[2] = "user.name";
- paraValues[0] = modTime;
- paraValues[1] = acsTime;
- paraValues[2] = user;
-
- return createQueryURL(host, nnPort, path, "SETTIMES",
- 3, paraNames, paraValues, url);
-}
-
-int createUrlForNnWRITE(const char *host, int nnPort,
- const char *path, const char *user,
- int16_t replication, size_t blockSize, char **url)
-{
- int strlength;
- char repStr[SHORT_STR_LEN], blockSizeStr[LONG_STR_LEN];
- const char *paraNames[4], *paraValues[4];
-
- memset(repStr, 0, SHORT_STR_LEN);
- memset(blockSizeStr, 0, LONG_STR_LEN);
- if (replication > 0) {
- strlength = snprintf(repStr, SHORT_STR_LEN, "%u", replication);
- if (strlength < 0 || strlength >= SHORT_STR_LEN) {
- return EIO;
- }
- }
- if (blockSize > 0) {
- strlength = snprintf(blockSizeStr, LONG_STR_LEN, "%lu", blockSize);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- }
- paraNames[0] = "overwrite";
- paraNames[1] = "replication";
- paraNames[2] = "blocksize";
- paraNames[3] = "user.name";
- paraValues[0] = "true";
- paraValues[1] = repStr;
- paraValues[2] = blockSizeStr;
- paraValues[3] = user;
-
- return createQueryURL(host, nnPort, path, "CREATE",
- 4, paraNames, paraValues, url);
-}
-
-int createUrlForSETREPLICATION(const char *host, int nnPort,
- const char *path, int16_t replication,
- const char *user, char **url)
-{
- char repStr[SHORT_STR_LEN];
- const char *paraNames[2], *paraValues[2];
- int strlength;
-
- memset(repStr, 0, SHORT_STR_LEN);
- if (replication > 0) {
- strlength = snprintf(repStr, SHORT_STR_LEN, "%u", replication);
- if (strlength < 0 || strlength >= SHORT_STR_LEN) {
- return EIO;
- }
- }
- paraNames[0] = "replication";
- paraNames[1] = "user.name";
- paraValues[0] = repStr;
- paraValues[1] = user;
-
- return createQueryURL(host, nnPort, path, "SETREPLICATION",
- 2, paraNames, paraValues, url);
-}
-
-int createUrlForGetBlockLocations(const char *host, int nnPort,
- const char *path, size_t offset,
- size_t length, const char *user, char **url)
-{
- char offsetStr[LONG_STR_LEN], lengthStr[LONG_STR_LEN];
- const char *paraNames[3], *paraValues[3];
- int strlength;
-
- memset(offsetStr, 0, LONG_STR_LEN);
- memset(lengthStr, 0, LONG_STR_LEN);
- if (offset > 0) {
- strlength = snprintf(offsetStr, LONG_STR_LEN, "%lu", offset);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- }
- if (length > 0) {
- strlength = snprintf(lengthStr, LONG_STR_LEN, "%lu", length);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- }
- paraNames[0] = "offset";
- paraNames[1] = "length";
- paraNames[2] = "user.name";
- paraValues[0] = offsetStr;
- paraValues[1] = lengthStr;
- paraValues[2] = user;
-
- return createQueryURL(host, nnPort, path, "GET_BLOCK_LOCATIONS",
- 3, paraNames, paraValues, url);
-}
-
-int createUrlForReadFromDatanode(const char *dnHost, int dnPort,
- const char *path, size_t offset,
- size_t length, const char *user,
- const char *namenodeRpcAddr, char **url)
-{
- char offsetStr[LONG_STR_LEN], lengthStr[LONG_STR_LEN];
- const char *paraNames[4], *paraValues[4];
- int strlength;
-
- memset(offsetStr, 0, LONG_STR_LEN);
- memset(lengthStr, 0, LONG_STR_LEN);
- if (offset > 0) {
- strlength = snprintf(offsetStr, LONG_STR_LEN, "%lu", offset);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- }
- if (length > 0) {
- strlength = snprintf(lengthStr, LONG_STR_LEN, "%lu", length);
- if (strlength < 0 || strlength >= LONG_STR_LEN) {
- return EIO;
- }
- }
-
- paraNames[0] = "offset";
- paraNames[1] = "length";
- paraNames[2] = "user.name";
- paraNames[3] = "namenoderpcaddress";
- paraValues[0] = offsetStr;
- paraValues[1] = lengthStr;
- paraValues[2] = user;
- paraValues[3] = namenodeRpcAddr;
-
- return createQueryURL(dnHost, dnPort, path, "OPEN",
- 4, paraNames, paraValues, url);
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_query.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_query.h b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_query.h
deleted file mode 100644
index 432797b..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_http_query.h
+++ /dev/null
@@ -1,240 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-
-#ifndef _HDFS_HTTP_QUERY_H_
-#define _HDFS_HTTP_QUERY_H_
-
-#include <unistd.h> /* for size_t */
-#include <inttypes.h> /* for int16_t */
-
-/**
- * Create the URL for a MKDIR request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the dir to create
- * @param user User name
- * @param url Holding the generated URL for MKDIR request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForMKDIR(const char *host, int nnPort,
- const char *path, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a MKDIR (with mode) request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the dir to create
- * @param mode Mode of MKDIR
- * @param user User name
- * @param url Holding the generated URL for MKDIR request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForMKDIRwithMode(const char *host, int nnPort, const char *path,
- int mode, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a RENAME request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param srcpath Source path
- * @param dstpath Destination path
- * @param user User name
- * @param url Holding the generated URL for RENAME request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForRENAME(const char *host, int nnPort, const char *srcpath,
- const char *dstpath, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a CHMOD request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Target path
- * @param mode New mode for the file
- * @param user User name
- * @param url Holding the generated URL for CHMOD request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForCHMOD(const char *host, int nnPort, const char *path,
- int mode, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a GETFILESTATUS request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the target file
- * @param user User name
- * @param url Holding the generated URL for GETFILESTATUS request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForGetFileStatus(const char *host, int nnPort,
- const char *path, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a LISTSTATUS request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the directory for listing
- * @param user User name
- * @param url Holding the generated URL for LISTSTATUS request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForLS(const char *host, int nnPort,
- const char *path, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a DELETE request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the file to be deletected
- * @param recursive Whether or not to delete in a recursive way
- * @param user User name
- * @param url Holding the generated URL for DELETE request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForDELETE(const char *host, int nnPort, const char *path,
- int recursive, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a CHOWN request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the target
- * @param owner New owner
- * @param group New group
- * @param user User name
- * @param url Holding the generated URL for CHOWN request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForCHOWN(const char *host, int nnPort, const char *path,
- const char *owner, const char *group, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a OPEN/READ request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the file to read
- * @param user User name
- * @param offset Offset for reading (the start position for this read)
- * @param length Length of the file to read
- * @param url Holding the generated URL for OPEN/READ request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForOPEN(const char *host, int nnPort, const char *path,
- const char *user, size_t offset, size_t length,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a UTIMES (update time) request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the file for updating time
- * @param mTime Modified time to set
- * @param aTime Access time to set
- * @param user User name
- * @param url Holding the generated URL for UTIMES request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForUTIMES(const char *host, int nnPort, const char *path,
- long unsigned mTime, long unsigned aTime,
- const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a WRITE/CREATE request (sent to NameNode)
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the dir to create
- * @param user User name
- * @param replication Number of replication of the file
- * @param blockSize Size of the block for the file
- * @param url Holding the generated URL for WRITE request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForNnWRITE(const char *host, int nnPort, const char *path,
- const char *user, int16_t replication, size_t blockSize,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for an APPEND request (sent to NameNode)
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the file for appending
- * @param user User name
- * @param url Holding the generated URL for APPEND request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForNnAPPEND(const char *host, int nnPort,
- const char *path, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a SETREPLICATION request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the target file
- * @param replication New replication number
- * @param user User name
- * @param url Holding the generated URL for SETREPLICATION request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForSETREPLICATION(const char *host, int nnPort, const char *path,
- int16_t replication, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-/**
- * Create the URL for a GET_BLOCK_LOCATIONS request
- *
- * @param host The hostname of the NameNode
- * @param nnPort Port of the NameNode
- * @param path Path of the target file
- * @param offset The offset in the file
- * @param length Length of the file content
- * @param user User name
- * @param url Holding the generated URL for GET_BLOCK_LOCATIONS request
- * @return 0 on success and non-zero value on errors
- */
-int createUrlForGetBlockLocations(const char *host, int nnPort,
- const char *path, size_t offset,
- size_t length, const char *user,
- char **url) __attribute__ ((warn_unused_result));
-
-
-#endif //_HDFS_HTTP_QUERY_H_
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.c b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.c
deleted file mode 100644
index 178fb9d..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.c
+++ /dev/null
@@ -1,654 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "exception.h"
-#include "hdfs.h" /* for hdfsFileInfo */
-#include "hdfs_json_parser.h"
-
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <jansson.h>
-
-static const char * const temporaryRedirectCode = "307 TEMPORARY_REDIRECT";
-static const char * const twoHundredOKCode = "200 OK";
-static const char * const twoHundredOneCreatedCode = "201 Created";
-static const char * const httpHeaderString = "HTTP/1.1";
-
-/**
- * Exception information after calling JSON operations
- */
-struct jsonException {
- const char *exception;
- const char *javaClassName;
- const char *message;
-};
-
-/** Print out the JSON exception information */
-static int printJsonExceptionV(struct jsonException *exc, int noPrintFlags,
- const char *fmt, va_list ap)
-{
- char *javaClassName = NULL;
- int excErrno = EINTERNAL, shouldPrint = 0;
- if (!exc) {
- fprintf(stderr, "printJsonExceptionV: the jsonException is NULL\n");
- return EINTERNAL;
- }
- javaClassName = strdup(exc->javaClassName);
- if (!javaClassName) {
- fprintf(stderr, "printJsonExceptionV: internal out of memory error\n");
- return EINTERNAL;
- }
- getExceptionInfo(javaClassName, noPrintFlags, &excErrno, &shouldPrint);
- free(javaClassName);
-
- if (shouldPrint) {
- vfprintf(stderr, fmt, ap);
- fprintf(stderr, " error:\n");
- fprintf(stderr, "Exception: %s\nJavaClassName: %s\nMessage: %s\n",
- exc->exception, exc->javaClassName, exc->message);
- }
-
- free(exc);
- return excErrno;
-}
-
-/**
- * Print out JSON exception information.
- *
- * @param exc The exception information to print and free
- * @param noPrintFlags Flags which determine which exceptions we should NOT
- * print.
- * @param fmt Printf-style format list
- * @param ... Printf-style varargs
- *
- * @return The POSIX error number associated with the exception
- * object.
- */
-static int printJsonException(struct jsonException *exc, int noPrintFlags,
- const char *fmt, ...)
-{
- va_list ap;
- int ret = 0;
-
- va_start(ap, fmt);
- ret = printJsonExceptionV(exc, noPrintFlags, fmt, ap);
- va_end(ap);
- return ret;
-}
-
-/** Parse the exception information from JSON */
-static struct jsonException *parseJsonException(json_t *jobj)
-{
- const char *key = NULL;
- json_t *value = NULL;
- struct jsonException *exception = NULL;
- void *iter = NULL;
-
- exception = calloc(1, sizeof(*exception));
- if (!exception) {
- return NULL;
- }
-
- iter = json_object_iter(jobj);
- while (iter) {
- key = json_object_iter_key(iter);
- value = json_object_iter_value(iter);
-
- if (!strcmp(key, "exception")) {
- exception->exception = json_string_value(value);
- } else if (!strcmp(key, "javaClassName")) {
- exception->javaClassName = json_string_value(value);
- } else if (!strcmp(key, "message")) {
- exception->message = json_string_value(value);
- }
-
- iter = json_object_iter_next(jobj, iter);
- }
- return exception;
-}
-
-/**
- * Parse the exception information which is presented in JSON
- *
- * @param content Exception information in JSON
- * @return jsonException for printing out
- */
-static struct jsonException *parseException(const char *content)
-{
- json_error_t error;
- size_t flags = 0;
- const char *key = NULL;
- json_t *value;
- json_t *jobj;
- struct jsonException *exception = NULL;
-
- if (!content) {
- return NULL;
- }
- jobj = json_loads(content, flags, &error);
- if (!jobj) {
- fprintf(stderr, "JSon parsing error: on line %d: %s\n",
- error.line, error.text);
- return NULL;
- }
- void *iter = json_object_iter(jobj);
- while(iter) {
- key = json_object_iter_key(iter);
- value = json_object_iter_value(iter);
-
- if (!strcmp(key, "RemoteException") &&
- json_typeof(value) == JSON_OBJECT) {
- exception = parseJsonException(value);
- break;
- }
- iter = json_object_iter_next(jobj, iter);
- }
-
- json_decref(jobj);
- return exception;
-}
-
-/**
- * Parse the response information which uses TRUE/FALSE
- * to indicate whether the operation succeeded
- *
- * @param response Response information
- * @return 0 to indicate success
- */
-static int parseBoolean(const char *response)
-{
- json_t *root, *value;
- json_error_t error;
- size_t flags = 0;
- int result = 0;
-
- root = json_loads(response, flags, &error);
- if (!root) {
- fprintf(stderr, "JSon parsing error: on line %d: %s\n",
- error.line, error.text);
- return EIO;
- }
- void *iter = json_object_iter(root);
- value = json_object_iter_value(iter);
- if (json_typeof(value) == JSON_TRUE) {
- result = 0;
- } else {
- result = EIO; // FALSE means error in remote NN/DN
- }
- json_decref(root);
- return result;
-}
-
-int parseMKDIR(const char *response)
-{
- return parseBoolean(response);
-}
-
-int parseRENAME(const char *response)
-{
- return parseBoolean(response);
-}
-
-int parseDELETE(const char *response)
-{
- return parseBoolean(response);
-}
-
-int parseSETREPLICATION(const char *response)
-{
- return parseBoolean(response);
-}
-
-/**
- * Check the header of response to see if it's 200 OK
- *
- * @param header Header information for checking
- * @param content Stores exception information if there are errors
- * @param operation Indicate the operation for exception printing
- * @return 0 for success
- */
-static int checkHeader(const char *header, const char *content,
- const char *operation)
-{
- char *result = NULL;
- const char delims[] = ":";
- char *savepter;
- int ret = 0;
-
- if (!header || strncmp(header, "HTTP/", strlen("HTTP/"))) {
- return EINVAL;
- }
- if (!(strstr(header, twoHundredOKCode)) ||
- !(result = strstr(header, "Content-Length"))) {
- struct jsonException *exc = parseException(content);
- if (exc) {
- ret = printJsonException(exc, PRINT_EXC_ALL,
- "Calling WEBHDFS (%s)", operation);
- } else {
- ret = EIO;
- }
- return ret;
- }
- result = strtok_r(result, delims, &savepter);
- result = strtok_r(NULL, delims, &savepter);
- while (isspace(*result)) {
- result++;
- }
- // Content-Length should be equal to 0,
- // and the string should be "0\r\nServer"
- if (strncmp(result, "0\r\n", 3)) {
- ret = EIO;
- }
- return ret;
-}
-
-int parseCHMOD(const char *header, const char *content)
-{
- return checkHeader(header, content, "CHMOD");
-}
-
-int parseCHOWN(const char *header, const char *content)
-{
- return checkHeader(header, content, "CHOWN");
-}
-
-int parseUTIMES(const char *header, const char *content)
-{
- return checkHeader(header, content, "SETTIMES");
-}
-
-/**
- * Check if the header contains correct information
- * ("307 TEMPORARY_REDIRECT" and "Location")
- *
- * @param header Header for parsing
- * @param content Contains exception information
- * if the remote operation failed
- * @param operation Specify the remote operation when printing out exception
- * @return 0 for success
- */
-static int checkRedirect(const char *header,
- const char *content, const char *operation)
-{
- const char *locTag = "Location";
- int ret = 0, offset = 0;
-
- // The header must start with "HTTP/1.1"
- if (!header || strncmp(header, httpHeaderString,
- strlen(httpHeaderString))) {
- return EINVAL;
- }
-
- offset += strlen(httpHeaderString);
- while (isspace(header[offset])) {
- offset++;
- }
- // Looking for "307 TEMPORARY_REDIRECT" in header
- if (strncmp(header + offset, temporaryRedirectCode,
- strlen(temporaryRedirectCode))) {
- // Process possible exception information
- struct jsonException *exc = parseException(content);
- if (exc) {
- ret = printJsonException(exc, PRINT_EXC_ALL,
- "Calling WEBHDFS (%s)", operation);
- } else {
- ret = EIO;
- }
- return ret;
- }
- // Here we just simply check if header contains "Location" tag,
- // detailed processing is in parseDnLoc
- if (!(strstr(header, locTag))) {
- ret = EIO;
- }
- return ret;
-}
-
-int parseNnWRITE(const char *header, const char *content)
-{
- return checkRedirect(header, content, "Write(NameNode)");
-}
-
-int parseNnAPPEND(const char *header, const char *content)
-{
- return checkRedirect(header, content, "Append(NameNode)");
-}
-
-/** 0 for success , -1 for out of range, other values for error */
-int parseOPEN(const char *header, const char *content)
-{
- int ret = 0, offset = 0;
-
- if (!header || strncmp(header, httpHeaderString,
- strlen(httpHeaderString))) {
- return EINVAL;
- }
-
- offset += strlen(httpHeaderString);
- while (isspace(header[offset])) {
- offset++;
- }
- if (strncmp(header + offset, temporaryRedirectCode,
- strlen(temporaryRedirectCode)) ||
- !strstr(header, twoHundredOKCode)) {
- struct jsonException *exc = parseException(content);
- if (exc) {
- // If the exception is an IOException and it is because
- // the offset is out of the range, do not print out the exception
- if (!strcasecmp(exc->exception, "IOException") &&
- strstr(exc->message, "out of the range")) {
- ret = -1;
- } else {
- ret = printJsonException(exc, PRINT_EXC_ALL,
- "Calling WEBHDFS (OPEN)");
- }
- } else {
- ret = EIO;
- }
- }
- return ret;
-}
-
-int parseDnLoc(char *content, char **dn)
-{
- char *url = NULL, *dnLocation = NULL, *savepter, *tempContent;
- const char *prefix = "Location: http://";
- const char *prefixToRemove = "Location: ";
- const char *delims = "\r\n";
-
- tempContent = strdup(content);
- if (!tempContent) {
- return ENOMEM;
- }
-
- dnLocation = strtok_r(tempContent, delims, &savepter);
- while (dnLocation && strncmp(dnLocation, "Location:",
- strlen("Location:"))) {
- dnLocation = strtok_r(NULL, delims, &savepter);
- }
- if (!dnLocation) {
- return EIO;
- }
-
- while (isspace(*dnLocation)) {
- dnLocation++;
- }
- if (strncmp(dnLocation, prefix, strlen(prefix))) {
- return EIO;
- }
- url = strdup(dnLocation + strlen(prefixToRemove));
- if (!url) {
- return ENOMEM;
- }
- *dn = url;
- return 0;
-}
-
-int parseDnWRITE(const char *header, const char *content)
-{
- int ret = 0;
- if (header == NULL || header[0] == '\0' ||
- strncmp(header, "HTTP/", strlen("HTTP/"))) {
- return EINVAL;
- }
- if (!(strstr(header, twoHundredOneCreatedCode))) {
- struct jsonException *exc = parseException(content);
- if (exc) {
- ret = printJsonException(exc, PRINT_EXC_ALL,
- "Calling WEBHDFS (WRITE(DataNode))");
- } else {
- ret = EIO;
- }
- }
- return ret;
-}
-
-int parseDnAPPEND(const char *header, const char *content)
-{
- int ret = 0;
-
- if (header == NULL || header[0] == '\0' ||
- strncmp(header, "HTTP/", strlen("HTTP/"))) {
- return EINVAL;
- }
- if (!(strstr(header, twoHundredOKCode))) {
- struct jsonException *exc = parseException(content);
- if (exc) {
- ret = printJsonException(exc, PRINT_EXC_ALL,
- "Calling WEBHDFS (APPEND(DataNode))");
- } else {
- ret = EIO;
- }
- }
- return ret;
-}
-
-/**
- * Retrieve file status from the JSON object
- *
- * @param jobj JSON object for parsing, which contains
- * file status information
- * @param fileStat hdfsFileInfo handle to hold file status information
- * @return 0 on success
- */
-static int parseJsonForFileStatus(json_t *jobj, hdfsFileInfo *fileStat)
-{
- const char *key, *tempstr;
- json_t *value;
- void *iter = NULL;
-
- iter = json_object_iter(jobj);
- while (iter) {
- key = json_object_iter_key(iter);
- value = json_object_iter_value(iter);
-
- if (!strcmp(key, "accessTime")) {
- // json field contains time in milliseconds,
- // hdfsFileInfo is counted in seconds
- fileStat->mLastAccess = json_integer_value(value) / 1000;
- } else if (!strcmp(key, "blockSize")) {
- fileStat->mBlockSize = json_integer_value(value);
- } else if (!strcmp(key, "length")) {
- fileStat->mSize = json_integer_value(value);
- } else if (!strcmp(key, "modificationTime")) {
- fileStat->mLastMod = json_integer_value(value) / 1000;
- } else if (!strcmp(key, "replication")) {
- fileStat->mReplication = json_integer_value(value);
- } else if (!strcmp(key, "group")) {
- fileStat->mGroup = strdup(json_string_value(value));
- if (!fileStat->mGroup) {
- return ENOMEM;
- }
- } else if (!strcmp(key, "owner")) {
- fileStat->mOwner = strdup(json_string_value(value));
- if (!fileStat->mOwner) {
- return ENOMEM;
- }
- } else if (!strcmp(key, "pathSuffix")) {
- fileStat->mName = strdup(json_string_value(value));
- if (!fileStat->mName) {
- return ENOMEM;
- }
- } else if (!strcmp(key, "permission")) {
- tempstr = json_string_value(value);
- fileStat->mPermissions = (short) strtol(tempstr, NULL, 8);
- } else if (!strcmp(key, "type")) {
- tempstr = json_string_value(value);
- if (!strcmp(tempstr, "DIRECTORY")) {
- fileStat->mKind = kObjectKindDirectory;
- } else {
- fileStat->mKind = kObjectKindFile;
- }
- }
- // Go to the next key-value pair in the json object
- iter = json_object_iter_next(jobj, iter);
- }
- return 0;
-}
-
-int parseGFS(const char *response, hdfsFileInfo *fileStat, int printError)
-{
- int ret = 0, printFlag;
- json_error_t error;
- size_t flags = 0;
- json_t *jobj, *value;
- const char *key;
- void *iter = NULL;
-
- if (!response || !fileStat) {
- return EIO;
- }
- jobj = json_loads(response, flags, &error);
- if (!jobj) {
- fprintf(stderr, "error while parsing json: on line %d: %s\n",
- error.line, error.text);
- return EIO;
- }
- iter = json_object_iter(jobj);
- key = json_object_iter_key(iter);
- value = json_object_iter_value(iter);
- if (json_typeof(value) == JSON_OBJECT) {
- if (!strcmp(key, "RemoteException")) {
- struct jsonException *exception = parseJsonException(value);
- if (exception) {
- if (printError) {
- printFlag = PRINT_EXC_ALL;
- } else {
- printFlag = NOPRINT_EXC_FILE_NOT_FOUND |
- NOPRINT_EXC_ACCESS_CONTROL |
- NOPRINT_EXC_PARENT_NOT_DIRECTORY;
- }
- ret = printJsonException(exception, printFlag,
- "Calling WEBHDFS GETFILESTATUS");
- } else {
- ret = EIO;
- }
- } else if (!strcmp(key, "FileStatus")) {
- ret = parseJsonForFileStatus(value, fileStat);
- } else {
- ret = EIO;
- }
-
- } else {
- ret = EIO;
- }
-
- json_decref(jobj);
- return ret;
-}
-
-/**
- * Parse the JSON array. Called to parse the result of
- * the LISTSTATUS operation. Thus each element of the JSON array is
- * a JSON object with the information of a file entry contained
- * in the folder.
- *
- * @param jobj The JSON array to be parsed
- * @param fileStat The hdfsFileInfo handle used to
- * store a group of file information
- * @param numEntries Capture the number of files in the folder
- * @return 0 for success
- */
-static int parseJsonArrayForFileStatuses(json_t *jobj, hdfsFileInfo **fileStat,
- int *numEntries)
-{
- json_t *jvalue = NULL;
- int i = 0, ret = 0, arraylen = 0;
- hdfsFileInfo *fileInfo = NULL;
-
- arraylen = (int) json_array_size(jobj);
- if (arraylen > 0) {
- fileInfo = calloc(arraylen, sizeof(hdfsFileInfo));
- if (!fileInfo) {
- return ENOMEM;
- }
- }
- for (i = 0; i < arraylen; i++) {
- //Getting the array element at position i
- jvalue = json_array_get(jobj, i);
- if (json_is_object(jvalue)) {
- ret = parseJsonForFileStatus(jvalue, &fileInfo[i]);
- if (ret) {
- goto done;
- }
- } else {
- ret = EIO;
- goto done;
- }
- }
-done:
- if (ret) {
- free(fileInfo);
- } else {
- *numEntries = arraylen;
- *fileStat = fileInfo;
- }
- return ret;
-}
-
-int parseLS(const char *response, hdfsFileInfo **fileStats, int *numOfEntries)
-{
- int ret = 0;
- json_error_t error;
- size_t flags = 0;
- json_t *jobj, *value;
- const char *key;
- void *iter = NULL;
-
- if (!response || response[0] == '\0' || !fileStats) {
- return EIO;
- }
- jobj = json_loads(response, flags, &error);
- if (!jobj) {
- fprintf(stderr, "error while parsing json: on line %d: %s\n",
- error.line, error.text);
- return EIO;
- }
-
- iter = json_object_iter(jobj);
- key = json_object_iter_key(iter);
- value = json_object_iter_value(iter);
- if (json_typeof(value) == JSON_OBJECT) {
- if (!strcmp(key, "RemoteException")) {
- struct jsonException *exception = parseJsonException(value);
- if (exception) {
- ret = printJsonException(exception, PRINT_EXC_ALL,
- "Calling WEBHDFS GETFILESTATUS");
- } else {
- ret = EIO;
- }
- } else if (!strcmp(key, "FileStatuses")) {
- iter = json_object_iter(value);
- value = json_object_iter_value(iter);
- if (json_is_array(value)) {
- ret = parseJsonArrayForFileStatuses(value, fileStats,
- numOfEntries);
- } else {
- ret = EIO;
- }
- } else {
- ret = EIO;
- }
- } else {
- ret = EIO;
- }
-
- json_decref(jobj);
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.h b/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.h
deleted file mode 100644
index c5f2f9c..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.h
+++ /dev/null
@@ -1,178 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-#ifndef _HDFS_JSON_PARSER_H_
-#define _HDFS_JSON_PARSER_H_
-
-/**
- * Parse the response for MKDIR request. The response uses TRUE/FALSE
- * to indicate whether the operation succeeded.
- *
- * @param response The response information to parse.
- * @return 0 for success
- */
-int parseMKDIR(const char *response);
-
-/**
- * Parse the response for RENAME request. The response uses TRUE/FALSE
- * to indicate whether the operation succeeded.
- *
- * @param response The response information to parse.
- * @return 0 for success
- */
-int parseRENAME(const char *response);
-
-/**
- * Parse the response for DELETE request. The response uses TRUE/FALSE
- * to indicate whether the operation succeeded.
- *
- * @param response The response information to parse.
- * @return 0 for success
- */
-int parseDELETE(const char *response);
-
-/**
- * Parse the response for SETREPLICATION request. The response uses TRUE/FALSE
- * to indicate whether the operation succeeded.
- *
- * @param response The response information to parse.
- * @return 0 for success
- */
-int parseSETREPLICATION(const char *response);
-
-/**
- * Parse the response for OPEN (read) request. A successful operation
- * will return "200 OK".
- *
- * @param response The response information for parsing
- * @return 0 for success , -1 for out of range, other values for error
- */
-int parseOPEN(const char *header, const char *content);
-
-/**
- * Parse the response for WRITE (from NameNode) request.
- * A successful operation should return "307 TEMPORARY_REDIRECT" in its header.
- *
- * @param header The header of the http response
- * @param content If failing, the exception message
- * sent from NameNode is stored in content
- * @return 0 for success
- */
-int parseNnWRITE(const char *header, const char *content);
-
-/**
- * Parse the response for WRITE (from DataNode) request.
- * A successful operation should return "201 Created" in its header.
- *
- * @param header The header of the http response
- * @param content If failing, the exception message
- * sent from DataNode is stored in content
- * @return 0 for success
- */
-int parseDnWRITE(const char *header, const char *content);
-
-/**
- * Parse the response for APPEND (sent from NameNode) request.
- * A successful operation should return "307 TEMPORARY_REDIRECT" in its header.
- *
- * @param header The header of the http response
- * @param content If failing, the exception message
- * sent from NameNode is stored in content
- * @return 0 for success
- */
-int parseNnAPPEND(const char *header, const char *content);
-
-/**
- * Parse the response for APPEND (from DataNode) request.
- * A successful operation should return "200 OK" in its header.
- *
- * @param header The header of the http response
- * @param content If failing, the exception message
- * sent from DataNode is stored in content
- * @return 0 for success
- */
-int parseDnAPPEND(const char *header, const char *content);
-
-/**
- * Parse the response (from NameNode) to get the location information
- * of the DataNode that should be contacted for the following write operation.
- *
- * @param content Content of the http header
- * @param dn To store the location of the DataNode for writing
- * @return 0 for success
- */
-int parseDnLoc(char *content, char **dn) __attribute__ ((warn_unused_result));
-
-/**
- * Parse the response for GETFILESTATUS operation.
- *
- * @param response Response to parse. Its detailed format is specified in
- * "http://hadoop.apache.org/docs/stable/webhdfs.html#GETFILESTATUS"
- * @param fileStat A hdfsFileInfo handle for holding file information
- * @param printError Whether or not print out exception
- * when file does not exist
- * @return 0 for success, non-zero value to indicate error
- */
-int parseGFS(const char *response, hdfsFileInfo *fileStat, int printError);
-
-/**
- * Parse the response for LISTSTATUS operation.
- *
- * @param response Response to parse. Its detailed format is specified in
- * "http://hadoop.apache.org/docs/r1.0.3/webhdfs.html#LISTSTATUS"
- * @param fileStats Pointer pointing to a list of hdfsFileInfo handles
- * holding file/dir information in the directory
- * @param numEntries After parsing, the value of this parameter indicates
- * the number of file entries.
- * @return 0 for success, non-zero value to indicate error
- */
-int parseLS(const char *response, hdfsFileInfo **fileStats, int *numOfEntries);
-
-/**
- * Parse the response for CHOWN request.
- * A successful operation should contains "200 OK" in its header,
- * and the Content-Length should be 0.
- *
- * @param header The header of the http response
- * @param content If failing, the exception message is stored in content
- * @return 0 for success
- */
-int parseCHOWN(const char *header, const char *content);
-
-/**
- * Parse the response for CHMOD request.
- * A successful operation should contains "200 OK" in its header,
- * and the Content-Length should be 0.
- *
- * @param header The header of the http response
- * @param content If failing, the exception message is stored in content
- * @return 0 for success
- */
-int parseCHMOD(const char *header, const char *content);
-
-/**
- * Parse the response for SETTIMES request.
- * A successful operation should contains "200 OK" in its header,
- * and the Content-Length should be 0.
- *
- * @param header The header of the http response
- * @param content If failing, the exception message is stored in content
- * @return 0 for success
- */
-int parseUTIMES(const char *header, const char *content);
-
-#endif //_HDFS_JSON_PARSER_H_
[27/35] hadoop git commit: HADOOP-12465. Incorrect javadoc in
WritableUtils.java. Contributed by Jagadesh Kiran N.
Posted by ji...@apache.org.
HADOOP-12465. Incorrect javadoc in WritableUtils.java. Contributed by Jagadesh Kiran N.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/7fbf69bf
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/7fbf69bf
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/7fbf69bf
Branch: refs/heads/HDFS-8966
Commit: 7fbf69bf47bb733f95b4afd733f9b65e1e7f2b46
Parents: 99e5204
Author: Akira Ajisaka <aa...@apache.org>
Authored: Thu Oct 8 06:08:28 2015 +0900
Committer: Akira Ajisaka <aa...@apache.org>
Committed: Thu Oct 8 06:08:28 2015 +0900
----------------------------------------------------------------------
hadoop-common-project/hadoop-common/CHANGES.txt | 3 +++
.../src/main/java/org/apache/hadoop/io/WritableUtils.java | 8 ++++----
2 files changed, 7 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/7fbf69bf/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index fd6e2f1..3eb106f 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -1312,6 +1312,9 @@ Release 2.7.2 - UNRELEASED
HADOOP-12213. Interrupted exception can occur when Client#stop is called.
(Kuhu Shukla via ozawa)
+ HADOOP-12465. Incorrect javadoc in WritableUtils.java.
+ (Jagadesh Kiran N via aajisaka)
+
Release 2.7.1 - 2015-07-06
INCOMPATIBLE CHANGES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/7fbf69bf/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/WritableUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/WritableUtils.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/WritableUtils.java
index ae615dd..e58e0e1 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/WritableUtils.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/WritableUtils.java
@@ -236,13 +236,13 @@ public final class WritableUtils {
/**
* Serializes an integer to a binary stream with zero-compressed encoding.
- * For -120 <= i <= 127, only one byte is used with the actual value.
+ * For -112 <= i <= 127, only one byte is used with the actual value.
* For other values of i, the first byte value indicates whether the
* integer is positive or negative, and the number of bytes that follow.
+ * If the first byte value v is between -113 and -116, the following integer
+ * is positive, with number of bytes that follow are -(v+112).
* If the first byte value v is between -121 and -124, the following integer
- * is positive, with number of bytes that follow are -(v+120).
- * If the first byte value v is between -125 and -128, the following integer
- * is negative, with number of bytes that follow are -(v+124). Bytes are
+ * is negative, with number of bytes that follow are -(v+120). Bytes are
* stored in the high-non-zero-byte-first order.
*
* @param stream Binary output stream
[07/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/thread_local_storage.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/thread_local_storage.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/thread_local_storage.c
deleted file mode 100644
index 2f70e2c..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/thread_local_storage.c
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "os/thread_local_storage.h"
-
-#include <jni.h>
-#include <pthread.h>
-#include <stdio.h>
-
-/** Key that allows us to retrieve thread-local storage */
-static pthread_key_t gTlsKey;
-
-/** nonzero if we succeeded in initializing gTlsKey. Protected by the jvmMutex */
-static int gTlsKeyInitialized = 0;
-
-/**
- * The function that is called whenever a thread with libhdfs thread local data
- * is destroyed.
- *
- * @param v The thread-local data
- */
-static void hdfsThreadDestructor(void *v)
-{
- JavaVM *vm;
- JNIEnv *env = v;
- jint ret;
-
- ret = (*env)->GetJavaVM(env, &vm);
- if (ret) {
- fprintf(stderr, "hdfsThreadDestructor: GetJavaVM failed with error %d\n",
- ret);
- (*env)->ExceptionDescribe(env);
- } else {
- (*vm)->DetachCurrentThread(vm);
- }
-}
-
-int threadLocalStorageGet(JNIEnv **env)
-{
- int ret = 0;
- if (!gTlsKeyInitialized) {
- ret = pthread_key_create(&gTlsKey, hdfsThreadDestructor);
- if (ret) {
- fprintf(stderr,
- "threadLocalStorageGet: pthread_key_create failed with error %d\n",
- ret);
- return ret;
- }
- gTlsKeyInitialized = 1;
- }
- *env = pthread_getspecific(gTlsKey);
- return ret;
-}
-
-int threadLocalStorageSet(JNIEnv *env)
-{
- int ret = pthread_setspecific(gTlsKey, env);
- if (ret) {
- fprintf(stderr,
- "threadLocalStorageSet: pthread_setspecific failed with error %d\n",
- ret);
- hdfsThreadDestructor(env);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/thread.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/thread.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/thread.h
deleted file mode 100644
index ae425d3..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/thread.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_THREAD_H
-#define LIBHDFS_THREAD_H
-
-/*
- * Defines abstraction over platform-specific threads.
- */
-
-#include "platform.h"
-
-/** Pointer to function to run in thread. */
-typedef void (*threadProcedure)(void *);
-
-/** Structure containing a thread's ID, starting address and argument. */
-typedef struct {
- threadId id;
- threadProcedure start;
- void *arg;
-} thread;
-
-/**
- * Creates and immediately starts a new thread.
- *
- * @param t thread to create
- * @return 0 if successful, non-zero otherwise
- */
-int threadCreate(thread *t);
-
-/**
- * Joins to the given thread, blocking if necessary.
- *
- * @param t thread to join
- * @return 0 if successful, non-zero otherwise
- */
-int threadJoin(const thread *t);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/thread_local_storage.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/thread_local_storage.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/thread_local_storage.h
deleted file mode 100644
index a40d567..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/thread_local_storage.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_THREAD_LOCAL_STORAGE_H
-#define LIBHDFS_THREAD_LOCAL_STORAGE_H
-
-/*
- * Defines abstraction over platform-specific thread-local storage. libhdfs
- * currently only needs thread-local storage for a single piece of data: the
- * thread's JNIEnv. For simplicity, this interface is defined in terms of
- * JNIEnv, not general-purpose thread-local storage of any arbitrary data.
- */
-
-#include <jni.h>
-
-/*
- * Most operating systems support the more efficient __thread construct, which
- * is initialized by the linker. The following macros use this technique on the
- * operating systems that support it.
- */
-#ifdef HAVE_BETTER_TLS
- #define THREAD_LOCAL_STORAGE_GET_QUICK() \
- static __thread JNIEnv *quickTlsEnv = NULL; \
- { \
- if (quickTlsEnv) { \
- return quickTlsEnv; \
- } \
- }
-
- #define THREAD_LOCAL_STORAGE_SET_QUICK(env) \
- { \
- quickTlsEnv = (env); \
- }
-#else
- #define THREAD_LOCAL_STORAGE_GET_QUICK()
- #define THREAD_LOCAL_STORAGE_SET_QUICK(env)
-#endif
-
-/**
- * Gets the JNIEnv in thread-local storage for the current thread. If the call
- * succeeds, and there is a JNIEnv associated with this thread, then returns 0
- * and populates env. If the call succeeds, but there is no JNIEnv associated
- * with this thread, then returns 0 and sets JNIEnv to NULL. If the call fails,
- * then returns non-zero. Only one thread at a time may execute this function.
- * The caller is responsible for enforcing mutual exclusion.
- *
- * @param env JNIEnv out parameter
- * @return 0 if successful, non-zero otherwise
- */
-int threadLocalStorageGet(JNIEnv **env);
-
-/**
- * Sets the JNIEnv in thread-local storage for the current thread.
- *
- * @param env JNIEnv to set
- * @return 0 if successful, non-zero otherwise
- */
-int threadLocalStorageSet(JNIEnv *env);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/inttypes.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/inttypes.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/inttypes.h
deleted file mode 100644
index a520d15..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/inttypes.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_INTTYPES_H
-#define LIBHDFS_INTTYPES_H
-
-/* On Windows, inttypes.h does not exist, so manually define what we need. */
-
-#define PRId64 "I64d"
-#define PRIu64 "I64u"
-typedef unsigned __int64 uint64_t;
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/mutexes.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/mutexes.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/mutexes.c
deleted file mode 100644
index 875f033..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/mutexes.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "os/mutexes.h"
-
-#include <windows.h>
-
-mutex hdfsHashMutex;
-mutex jvmMutex;
-
-/**
- * Unfortunately, there is no simple static initializer for a critical section.
- * Instead, the API requires calling InitializeCriticalSection. Since libhdfs
- * lacks an explicit initialization function, there is no obvious existing place
- * for the InitializeCriticalSection calls. To work around this, we define an
- * initialization function and instruct the linker to set a pointer to that
- * function as a user-defined global initializer. See discussion of CRT
- * Initialization:
- * http://msdn.microsoft.com/en-us/library/bb918180.aspx
- */
-static void __cdecl initializeMutexes(void) {
- InitializeCriticalSection(&hdfsHashMutex);
- InitializeCriticalSection(&jvmMutex);
-}
-#pragma section(".CRT$XCU", read)
-__declspec(allocate(".CRT$XCU"))
-const void (__cdecl *pInitialize)(void) = initializeMutexes;
-
-int mutexLock(mutex *m) {
- EnterCriticalSection(m);
- return 0;
-}
-
-int mutexUnlock(mutex *m) {
- LeaveCriticalSection(m);
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/platform.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/platform.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/platform.h
deleted file mode 100644
index 9eedfde..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/platform.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_PLATFORM_H
-#define LIBHDFS_PLATFORM_H
-
-#include <stdio.h>
-#include <windows.h>
-#include <winsock.h>
-
-/*
- * O_ACCMODE defined to match Linux definition.
- */
-#ifndef O_ACCMODE
-#define O_ACCMODE 0x0003
-#endif
-
-/*
- * Windows has a different name for its maximum path length constant.
- */
-#ifndef PATH_MAX
-#define PATH_MAX MAX_PATH
-#endif
-
-/*
- * Windows does not define EDQUOT and ESTALE in errno.h. The closest equivalents
- * are these constants from winsock.h.
- */
-#ifndef EDQUOT
-#define EDQUOT WSAEDQUOT
-#endif
-
-#ifndef ESTALE
-#define ESTALE WSAESTALE
-#endif
-
-/*
- * gcc-style type-checked format arguments are not supported on Windows, so just
- * stub this macro.
- */
-#define TYPE_CHECKED_PRINTF_FORMAT(formatArg, varArgs)
-
-/*
- * Define macros for various string formatting functions not defined on Windows.
- * Where possible, we reroute to one of the secure CRT variants. On Windows,
- * the preprocessor does support variadic macros, even though they weren't
- * defined until C99.
- */
-#define snprintf(str, size, format, ...) \
- _snprintf_s((str), (size), _TRUNCATE, (format), __VA_ARGS__)
-#define strncpy(dest, src, n) \
- strncpy_s((dest), (n), (src), _TRUNCATE)
-#define strtok_r(str, delim, saveptr) \
- strtok_s((str), (delim), (saveptr))
-#define vsnprintf(str, size, format, ...) \
- vsnprintf_s((str), (size), _TRUNCATE, (format), __VA_ARGS__)
-
-/*
- * Mutex data type defined as Windows CRITICAL_SECTION. A critical section (not
- * Windows mutex) is used, because libhdfs only needs synchronization of multiple
- * threads within a single process, not synchronization across process
- * boundaries.
- */
-typedef CRITICAL_SECTION mutex;
-
-/*
- * Thread data type defined as HANDLE to a Windows thread.
- */
-typedef HANDLE threadId;
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/thread.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/thread.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/thread.c
deleted file mode 100644
index f5cc2a7..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/thread.c
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "os/thread.h"
-
-#include <stdio.h>
-#include <windows.h>
-
-/**
- * Defines a helper function that adapts function pointer provided by caller to
- * the type required by CreateThread.
- *
- * @param toRun thread to run
- * @return DWORD result of running thread (always 0)
- */
-static DWORD WINAPI runThread(LPVOID toRun) {
- const thread *t = toRun;
- t->start(t->arg);
- return 0;
-}
-
-int threadCreate(thread *t) {
- DWORD ret = 0;
- HANDLE h;
- h = CreateThread(NULL, 0, runThread, t, 0, NULL);
- if (h) {
- t->id = h;
- } else {
- ret = GetLastError();
- fprintf(stderr, "threadCreate: CreateThread failed with error %d\n", ret);
- }
- return ret;
-}
-
-int threadJoin(const thread *t) {
- DWORD ret = WaitForSingleObject(t->id, INFINITE);
- switch (ret) {
- case WAIT_OBJECT_0:
- break;
- case WAIT_FAILED:
- ret = GetLastError();
- fprintf(stderr, "threadJoin: WaitForSingleObject failed with error %d\n",
- ret);
- break;
- default:
- fprintf(stderr, "threadJoin: WaitForSingleObject unexpected error %d\n",
- ret);
- break;
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/thread_local_storage.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/thread_local_storage.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/thread_local_storage.c
deleted file mode 100644
index 4c415e1..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/thread_local_storage.c
+++ /dev/null
@@ -1,172 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "os/thread_local_storage.h"
-
-#include <jni.h>
-#include <stdio.h>
-#include <windows.h>
-
-/** Key that allows us to retrieve thread-local storage */
-static DWORD gTlsIndex = TLS_OUT_OF_INDEXES;
-
-/**
- * If the current thread has a JNIEnv in thread-local storage, then detaches the
- * current thread from the JVM.
- */
-static void detachCurrentThreadFromJvm()
-{
- JNIEnv *env = NULL;
- JavaVM *vm;
- jint ret;
- if (threadLocalStorageGet(&env) || !env) {
- return;
- }
- ret = (*env)->GetJavaVM(env, &vm);
- if (ret) {
- fprintf(stderr,
- "detachCurrentThreadFromJvm: GetJavaVM failed with error %d\n",
- ret);
- (*env)->ExceptionDescribe(env);
- } else {
- (*vm)->DetachCurrentThread(vm);
- }
-}
-
-/**
- * Unlike pthreads, the Windows API does not seem to provide a convenient way to
- * hook a callback onto thread shutdown. However, the Windows portable
- * executable format does define a concept of thread-local storage callbacks.
- * Here, we define a function and instruct the linker to set a pointer to that
- * function in the segment for thread-local storage callbacks. See page 85 of
- * Microsoft Portable Executable and Common Object File Format Specification:
- * http://msdn.microsoft.com/en-us/gg463119.aspx
- * This technique only works for implicit linking (OS loads DLL on demand), not
- * for explicit linking (user code calls LoadLibrary directly). This effectively
- * means that we have a known limitation: libhdfs may not work correctly if a
- * Windows application attempts to use it via explicit linking.
- *
- * @param h module handle
- * @param reason the reason for calling the callback
- * @param pv reserved, unused
- */
-static void NTAPI tlsCallback(PVOID h, DWORD reason, PVOID pv)
-{
- DWORD tlsIndex;
- switch (reason) {
- case DLL_THREAD_DETACH:
- detachCurrentThreadFromJvm();
- break;
- case DLL_PROCESS_DETACH:
- detachCurrentThreadFromJvm();
- tlsIndex = gTlsIndex;
- gTlsIndex = TLS_OUT_OF_INDEXES;
- if (!TlsFree(tlsIndex)) {
- fprintf(stderr, "tlsCallback: TlsFree failed with error %d\n",
- GetLastError());
- }
- break;
- default:
- break;
- }
-}
-
-/*
- * A variable named _tls_used contains the TLS directory, which contains a list
- * of pointers to callback functions. Normally, the linker won't retain this
- * variable unless the executable has implicit thread-local variables, defined
- * using the __declspec(thread) extended storage-class modifier. libhdfs
- * doesn't use __declspec(thread), and we have no guarantee that the executable
- * linked to libhdfs will use __declspec(thread). By forcing the linker to
- * reference _tls_used, we guarantee that the binary retains the TLS directory.
- * See Microsoft Visual Studio 10.0/VC/crt/src/tlssup.c .
- */
-#ifdef _WIN64
-#pragma comment(linker, "/INCLUDE:_tls_used")
-#else
-#pragma comment(linker, "/INCLUDE:__tls_used")
-#endif
-
-/*
- * We must retain a pointer to the callback function. Force the linker to keep
- * this symbol, even though it appears that nothing in our source code uses it.
- */
-#ifdef _WIN64
-#pragma comment(linker, "/INCLUDE:pTlsCallback")
-#else
-#pragma comment(linker, "/INCLUDE:_pTlsCallback")
-#endif
-
-/*
- * Define constant pointer to our callback, and tell the linker to pin it into
- * the TLS directory so that it receives thread callbacks. Use external linkage
- * to protect against the linker discarding the seemingly unused symbol.
- */
-#pragma const_seg(".CRT$XLB")
-extern const PIMAGE_TLS_CALLBACK pTlsCallback;
-const PIMAGE_TLS_CALLBACK pTlsCallback = tlsCallback;
-#pragma const_seg()
-
-int threadLocalStorageGet(JNIEnv **env)
-{
- LPVOID tls;
- DWORD ret;
- if (TLS_OUT_OF_INDEXES == gTlsIndex) {
- gTlsIndex = TlsAlloc();
- if (TLS_OUT_OF_INDEXES == gTlsIndex) {
- fprintf(stderr,
- "threadLocalStorageGet: TlsAlloc failed with error %d\n",
- TLS_OUT_OF_INDEXES);
- return TLS_OUT_OF_INDEXES;
- }
- }
- tls = TlsGetValue(gTlsIndex);
- if (tls) {
- *env = tls;
- return 0;
- } else {
- ret = GetLastError();
- if (ERROR_SUCCESS == ret) {
- /* Thread-local storage contains NULL, because we haven't set it yet. */
- *env = NULL;
- return 0;
- } else {
- /*
- * The API call failed. According to documentation, TlsGetValue cannot
- * fail as long as the index is a valid index from a successful TlsAlloc
- * call. This error handling is purely defensive.
- */
- fprintf(stderr,
- "threadLocalStorageGet: TlsGetValue failed with error %d\n", ret);
- return ret;
- }
- }
-}
-
-int threadLocalStorageSet(JNIEnv *env)
-{
- DWORD ret = 0;
- if (!TlsSetValue(gTlsIndex, (LPVOID)env)) {
- ret = GetLastError();
- fprintf(stderr,
- "threadLocalStorageSet: TlsSetValue failed with error %d\n",
- ret);
- detachCurrentThreadFromJvm(env);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/unistd.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/unistd.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/unistd.h
deleted file mode 100644
index b82ce48..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/windows/unistd.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_UNISTD_H
-#define LIBHDFS_UNISTD_H
-
-/* On Windows, unistd.h does not exist, so manually define what we need. */
-
-#include <process.h> /* Declares getpid(). */
-#include <windows.h>
-
-/* Re-route sleep to Sleep, converting units from seconds to milliseconds. */
-#define sleep(seconds) Sleep((seconds) * 1000)
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_htable.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_htable.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_htable.c
deleted file mode 100644
index 0c3861b..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_htable.c
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "common/htable.h"
-#include "expect.h"
-#include "hdfs_test.h"
-
-#include <errno.h>
-#include <inttypes.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-// Disable type cast and loss of precision warnings, because the test
-// manipulates void* values manually on purpose.
-#ifdef WIN32
-#pragma warning(disable: 4244 4306)
-#endif
-
-static uint32_t simple_hash(const void *key, uint32_t size)
-{
- uintptr_t k = (uintptr_t)key;
- return ((13 + k) * 6367) % size;
-}
-
-static int simple_compare(const void *a, const void *b)
-{
- return a == b;
-}
-
-static void expect_102(void *f, void *k, void *v)
-{
- int *found_102 = f;
- uintptr_t key = (uintptr_t)k;
- uintptr_t val = (uintptr_t)v;
-
- if ((key == 2) && (val == 102)) {
- *found_102 = 1;
- } else {
- abort();
- }
-}
-
-static void *htable_pop_val(struct htable *ht, void *key)
-{
- void *old_key, *old_val;
-
- htable_pop(ht, key, &old_key, &old_val);
- return old_val;
-}
-
-int main(void)
-{
- struct htable *ht;
- int found_102 = 0;
-
- ht = htable_alloc(4, simple_hash, simple_compare);
- EXPECT_INT_EQ(0, htable_used(ht));
- EXPECT_INT_EQ(4, htable_capacity(ht));
- EXPECT_NULL(htable_get(ht, (void*)123));
- EXPECT_NULL(htable_pop_val(ht, (void*)123));
- EXPECT_ZERO(htable_put(ht, (void*)123, (void*)456));
- EXPECT_INT_EQ(456, (uintptr_t)htable_get(ht, (void*)123));
- EXPECT_INT_EQ(456, (uintptr_t)htable_pop_val(ht, (void*)123));
- EXPECT_NULL(htable_pop_val(ht, (void*)123));
-
- // Enlarge the hash table
- EXPECT_ZERO(htable_put(ht, (void*)1, (void*)101));
- EXPECT_ZERO(htable_put(ht, (void*)2, (void*)102));
- EXPECT_ZERO(htable_put(ht, (void*)3, (void*)103));
- EXPECT_INT_EQ(3, htable_used(ht));
- EXPECT_INT_EQ(8, htable_capacity(ht));
- EXPECT_INT_EQ(102, (uintptr_t)htable_get(ht, (void*)2));
- EXPECT_INT_EQ(101, (uintptr_t)htable_pop_val(ht, (void*)1));
- EXPECT_INT_EQ(103, (uintptr_t)htable_pop_val(ht, (void*)3));
- EXPECT_INT_EQ(1, htable_used(ht));
- htable_visit(ht, expect_102, &found_102);
- EXPECT_INT_EQ(1, found_102);
- htable_free(ht);
-
- fprintf(stderr, "SUCCESS.\n");
- return EXIT_SUCCESS;
-}
-
-// vim: ts=4:sw=4:tw=79:et
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_ops.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_ops.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_ops.c
deleted file mode 100644
index f564de4..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_ops.c
+++ /dev/null
@@ -1,540 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "hdfs.h"
-#include "hdfs_test.h"
-#include "platform.h"
-
-#include <inttypes.h>
-#include <jni.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <unistd.h>
-
-void permission_disp(short permissions, char *rtr) {
- int i;
- short permissionsId;
- char* perm;
- rtr[9] = '\0';
- for(i=2;i>=0;i--)
- {
- permissionsId = permissions >> (i * 3) & (short)7;
- switch(permissionsId) {
- case 7:
- perm = "rwx"; break;
- case 6:
- perm = "rw-"; break;
- case 5:
- perm = "r-x"; break;
- case 4:
- perm = "r--"; break;
- case 3:
- perm = "-wx"; break;
- case 2:
- perm = "-w-"; break;
- case 1:
- perm = "--x"; break;
- case 0:
- perm = "---"; break;
- default:
- perm = "???";
- }
- strncpy(rtr, perm, 3);
- rtr+=3;
- }
-}
-
-int main(int argc, char **argv) {
- const char *writePath = "/tmp/testfile.txt";
- const char *fileContents = "Hello, World!";
- const char *readPath = "/tmp/testfile.txt";
- const char *srcPath = "/tmp/testfile.txt";
- const char *dstPath = "/tmp/testfile2.txt";
- const char *slashTmp = "/tmp";
- const char *newDirectory = "/tmp/newdir";
- const char *newOwner = "root";
- const char *tuser = "nobody";
- const char *appendPath = "/tmp/appends";
- const char *userPath = "/tmp/usertestfile.txt";
-
- char buffer[32], buffer2[256], rdbuffer[32];
- tSize num_written_bytes, num_read_bytes;
- hdfsFS fs, lfs;
- hdfsFile writeFile, readFile, localFile, appendFile, userFile;
- tOffset currentPos, seekPos;
- int exists, totalResult, result, numEntries, i, j;
- const char *resp;
- hdfsFileInfo *fileInfo, *fileList, *finfo;
- char *buffer3;
- char permissions[10];
- char ***hosts;
- short newPerm = 0666;
- tTime newMtime, newAtime;
-
- fs = hdfsConnectNewInstance("default", 0);
- if(!fs) {
- fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
- exit(-1);
- }
-
- lfs = hdfsConnectNewInstance(NULL, 0);
- if(!lfs) {
- fprintf(stderr, "Oops! Failed to connect to 'local' hdfs!\n");
- exit(-1);
- }
-
- {
- //Write tests
-
- writeFile = hdfsOpenFile(fs, writePath, O_WRONLY|O_CREAT, 0, 0, 0);
- if(!writeFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", writePath);
- exit(-1);
- }
- fprintf(stderr, "Opened %s for writing successfully...\n", writePath);
- num_written_bytes =
- hdfsWrite(fs, writeFile, (void*)fileContents,
- (tSize)(strlen(fileContents)+1));
- if (num_written_bytes != strlen(fileContents) + 1) {
- fprintf(stderr, "Failed to write correct number of bytes - expected %d, got %d\n",
- (int)(strlen(fileContents) + 1), (int)num_written_bytes);
- exit(-1);
- }
- fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
-
- currentPos = -1;
- if ((currentPos = hdfsTell(fs, writeFile)) == -1) {
- fprintf(stderr,
- "Failed to get current file position correctly! Got %" PRId64 "!\n",
- currentPos);
- exit(-1);
- }
- fprintf(stderr, "Current position: %" PRId64 "\n", currentPos);
-
- if (hdfsFlush(fs, writeFile)) {
- fprintf(stderr, "Failed to 'flush' %s\n", writePath);
- exit(-1);
- }
- fprintf(stderr, "Flushed %s successfully!\n", writePath);
-
- if (hdfsHFlush(fs, writeFile)) {
- fprintf(stderr, "Failed to 'hflush' %s\n", writePath);
- exit(-1);
- }
- fprintf(stderr, "HFlushed %s successfully!\n", writePath);
-
- hdfsCloseFile(fs, writeFile);
- }
-
- {
- //Read tests
-
- exists = hdfsExists(fs, readPath);
-
- if (exists) {
- fprintf(stderr, "Failed to validate existence of %s\n", readPath);
- exit(-1);
- }
-
- readFile = hdfsOpenFile(fs, readPath, O_RDONLY, 0, 0, 0);
- if (!readFile) {
- fprintf(stderr, "Failed to open %s for reading!\n", readPath);
- exit(-1);
- }
-
- if (!hdfsFileIsOpenForRead(readFile)) {
- fprintf(stderr, "hdfsFileIsOpenForRead: we just opened a file "
- "with O_RDONLY, and it did not show up as 'open for "
- "read'\n");
- exit(-1);
- }
-
- fprintf(stderr, "hdfsAvailable: %d\n", hdfsAvailable(fs, readFile));
-
- seekPos = 1;
- if(hdfsSeek(fs, readFile, seekPos)) {
- fprintf(stderr, "Failed to seek %s for reading!\n", readPath);
- exit(-1);
- }
-
- currentPos = -1;
- if((currentPos = hdfsTell(fs, readFile)) != seekPos) {
- fprintf(stderr,
- "Failed to get current file position correctly! Got %" PRId64 "!\n",
- currentPos);
- exit(-1);
- }
- fprintf(stderr, "Current position: %" PRId64 "\n", currentPos);
-
- if (!hdfsFileUsesDirectRead(readFile)) {
- fprintf(stderr, "Direct read support incorrectly not detected "
- "for HDFS filesystem\n");
- exit(-1);
- }
-
- fprintf(stderr, "Direct read support detected for HDFS\n");
-
- // Test the direct read path
- if(hdfsSeek(fs, readFile, 0)) {
- fprintf(stderr, "Failed to seek %s for reading!\n", readPath);
- exit(-1);
- }
- memset(buffer, 0, sizeof(buffer));
- num_read_bytes = hdfsRead(fs, readFile, (void*)buffer,
- sizeof(buffer));
- if (strncmp(fileContents, buffer, strlen(fileContents)) != 0) {
- fprintf(stderr, "Failed to read (direct). Expected %s but got %s (%d bytes)\n",
- fileContents, buffer, num_read_bytes);
- exit(-1);
- }
- fprintf(stderr, "Read (direct) following %d bytes:\n%s\n",
- num_read_bytes, buffer);
- if (hdfsSeek(fs, readFile, 0L)) {
- fprintf(stderr, "Failed to seek to file start!\n");
- exit(-1);
- }
-
- // Disable the direct read path so that we really go through the slow
- // read path
- hdfsFileDisableDirectRead(readFile);
-
- num_read_bytes = hdfsRead(fs, readFile, (void*)buffer,
- sizeof(buffer));
- fprintf(stderr, "Read following %d bytes:\n%s\n",
- num_read_bytes, buffer);
-
- memset(buffer, 0, strlen(fileContents + 1));
-
- num_read_bytes = hdfsPread(fs, readFile, 0, (void*)buffer,
- sizeof(buffer));
- fprintf(stderr, "Read following %d bytes:\n%s\n",
- num_read_bytes, buffer);
-
- hdfsCloseFile(fs, readFile);
-
- // Test correct behaviour for unsupported filesystems
- localFile = hdfsOpenFile(lfs, writePath, O_WRONLY|O_CREAT, 0, 0, 0);
- if(!localFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", writePath);
- exit(-1);
- }
-
- num_written_bytes = hdfsWrite(lfs, localFile, (void*)fileContents,
- (tSize)(strlen(fileContents) + 1));
-
- hdfsCloseFile(lfs, localFile);
- localFile = hdfsOpenFile(lfs, writePath, O_RDONLY, 0, 0, 0);
-
- if (hdfsFileUsesDirectRead(localFile)) {
- fprintf(stderr, "Direct read support incorrectly detected for local "
- "filesystem\n");
- exit(-1);
- }
-
- hdfsCloseFile(lfs, localFile);
- }
-
- totalResult = 0;
- result = 0;
- {
- //Generic file-system operations
-
- fprintf(stderr, "hdfsCopy(remote-local): %s\n", ((result = hdfsCopy(fs, srcPath, lfs, srcPath)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsCopy(remote-remote): %s\n", ((result = hdfsCopy(fs, srcPath, fs, dstPath)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsMove(local-local): %s\n", ((result = hdfsMove(lfs, srcPath, lfs, dstPath)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsMove(remote-local): %s\n", ((result = hdfsMove(fs, srcPath, lfs, srcPath)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
- fprintf(stderr, "hdfsRename: %s\n", ((result = hdfsRename(fs, dstPath, srcPath)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsCopy(remote-remote): %s\n", ((result = hdfsCopy(fs, srcPath, fs, dstPath)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
- fprintf(stderr, "hdfsCreateDirectory: %s\n", ((result = hdfsCreateDirectory(fs, newDirectory)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
- fprintf(stderr, "hdfsSetReplication: %s\n", ((result = hdfsSetReplication(fs, srcPath, 2)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
- fprintf(stderr, "hdfsGetWorkingDirectory: %s\n", ((resp = hdfsGetWorkingDirectory(fs, buffer2, sizeof(buffer2))) != 0 ? buffer2 : "Failed!"));
- totalResult += (resp ? 0 : 1);
- fprintf(stderr, "hdfsSetWorkingDirectory: %s\n", ((result = hdfsSetWorkingDirectory(fs, slashTmp)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsGetWorkingDirectory: %s\n", ((resp = hdfsGetWorkingDirectory(fs, buffer2, sizeof(buffer2))) != 0 ? buffer2 : "Failed!"));
- totalResult += (resp ? 0 : 1);
-
- fprintf(stderr, "hdfsGetDefaultBlockSize: %" PRId64 "\n", hdfsGetDefaultBlockSize(fs));
- fprintf(stderr, "hdfsGetCapacity: %" PRId64 "\n", hdfsGetCapacity(fs));
- fprintf(stderr, "hdfsGetUsed: %" PRId64 "\n", hdfsGetUsed(fs));
-
- fileInfo = NULL;
- if((fileInfo = hdfsGetPathInfo(fs, slashTmp)) != NULL) {
- fprintf(stderr, "hdfsGetPathInfo - SUCCESS!\n");
- fprintf(stderr, "Name: %s, ", fileInfo->mName);
- fprintf(stderr, "Type: %c, ", (char)(fileInfo->mKind));
- fprintf(stderr, "Replication: %d, ", fileInfo->mReplication);
- fprintf(stderr, "BlockSize: %" PRId64 ", ", fileInfo->mBlockSize);
- fprintf(stderr, "Size: %" PRId64 ", ", fileInfo->mSize);
- fprintf(stderr, "LastMod: %s", ctime(&fileInfo->mLastMod));
- fprintf(stderr, "Owner: %s, ", fileInfo->mOwner);
- fprintf(stderr, "Group: %s, ", fileInfo->mGroup);
- permission_disp(fileInfo->mPermissions, permissions);
- fprintf(stderr, "Permissions: %d (%s)\n", fileInfo->mPermissions, permissions);
- hdfsFreeFileInfo(fileInfo, 1);
- } else {
- totalResult++;
- fprintf(stderr, "waah! hdfsGetPathInfo for %s - FAILED!\n", slashTmp);
- }
-
- fileList = 0;
- fileList = hdfsListDirectory(fs, newDirectory, &numEntries);
- if (!(fileList == NULL && numEntries == 0 && !errno)) {
- fprintf(stderr, "waah! hdfsListDirectory for empty %s - FAILED!\n", newDirectory);
- totalResult++;
- } else {
- fprintf(stderr, "hdfsListDirectory for empty %s - SUCCESS!\n", newDirectory);
- }
-
- fileList = 0;
- if((fileList = hdfsListDirectory(fs, slashTmp, &numEntries)) != NULL) {
- for(i=0; i < numEntries; ++i) {
- fprintf(stderr, "Name: %s, ", fileList[i].mName);
- fprintf(stderr, "Type: %c, ", (char)fileList[i].mKind);
- fprintf(stderr, "Replication: %d, ", fileList[i].mReplication);
- fprintf(stderr, "BlockSize: %" PRId64 ", ", fileList[i].mBlockSize);
- fprintf(stderr, "Size: %" PRId64 ", ", fileList[i].mSize);
- fprintf(stderr, "LastMod: %s", ctime(&fileList[i].mLastMod));
- fprintf(stderr, "Owner: %s, ", fileList[i].mOwner);
- fprintf(stderr, "Group: %s, ", fileList[i].mGroup);
- permission_disp(fileList[i].mPermissions, permissions);
- fprintf(stderr, "Permissions: %d (%s)\n", fileList[i].mPermissions, permissions);
- }
- hdfsFreeFileInfo(fileList, numEntries);
- } else {
- if (errno) {
- totalResult++;
- fprintf(stderr, "waah! hdfsListDirectory - FAILED!\n");
- } else {
- fprintf(stderr, "Empty directory!\n");
- }
- }
-
- hosts = hdfsGetHosts(fs, srcPath, 0, 1);
- if(hosts) {
- fprintf(stderr, "hdfsGetHosts - SUCCESS! ... \n");
- i=0;
- while(hosts[i]) {
- j = 0;
- while(hosts[i][j]) {
- fprintf(stderr,
- "\thosts[%d][%d] - %s\n", i, j, hosts[i][j]);
- ++j;
- }
- ++i;
- }
- } else {
- totalResult++;
- fprintf(stderr, "waah! hdfsGetHosts - FAILED!\n");
- }
-
- // setting tmp dir to 777 so later when connectAsUser nobody, we can write to it
-
- // chown write
- fprintf(stderr, "hdfsChown: %s\n", ((result = hdfsChown(fs, writePath, NULL, "users")) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsChown: %s\n", ((result = hdfsChown(fs, writePath, newOwner, NULL)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- // chmod write
- fprintf(stderr, "hdfsChmod: %s\n", ((result = hdfsChmod(fs, writePath, newPerm)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
-
-
- sleep(2);
- newMtime = time(NULL);
- newAtime = time(NULL);
-
- // utime write
- fprintf(stderr, "hdfsUtime: %s\n", ((result = hdfsUtime(fs, writePath, newMtime, newAtime)) != 0 ? "Failed!" : "Success!"));
-
- totalResult += result;
-
- // chown/chmod/utime read
- finfo = hdfsGetPathInfo(fs, writePath);
-
- fprintf(stderr, "hdfsChown read: %s\n", ((result = (strcmp(finfo->mOwner, newOwner))) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
- fprintf(stderr, "hdfsChmod read: %s\n", ((result = (finfo->mPermissions != newPerm)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
- // will later use /tmp/ as a different user so enable it
- fprintf(stderr, "hdfsChmod: %s\n", ((result = hdfsChmod(fs, "/tmp/", 0777)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
- fprintf(stderr,"newMTime=%ld\n",newMtime);
- fprintf(stderr,"curMTime=%ld\n",finfo->mLastMod);
-
-
- fprintf(stderr, "hdfsUtime read (mtime): %s\n", ((result = (finfo->mLastMod != newMtime)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
-
- // No easy way to turn on access times from hdfs_test right now
- // fprintf(stderr, "hdfsUtime read (atime): %s\n", ((result = (finfo->mLastAccess != newAtime)) != 0 ? "Failed!" : "Success!"));
- // totalResult += result;
-
- hdfsFreeFileInfo(finfo, 1);
-
- // Clean up
- fprintf(stderr, "hdfsDelete: %s\n", ((result = hdfsDelete(fs, newDirectory, 1)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsDelete: %s\n", ((result = hdfsDelete(fs, srcPath, 1)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsDelete: %s\n", ((result = hdfsDelete(lfs, srcPath, 1)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsDelete: %s\n", ((result = hdfsDelete(lfs, dstPath, 1)) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- fprintf(stderr, "hdfsExists: %s\n", ((result = hdfsExists(fs, newDirectory)) != 0 ? "Success!" : "Failed!"));
- totalResult += (result ? 0 : 1);
- }
-
- {
- // TEST APPENDS
-
- // CREATE
- appendFile = hdfsOpenFile(fs, appendPath, O_WRONLY, 0, 0, 0);
- if(!appendFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", appendPath);
- exit(-1);
- }
- fprintf(stderr, "Opened %s for writing successfully...\n", appendPath);
-
- buffer3 = "Hello,";
- num_written_bytes = hdfsWrite(fs, appendFile, (void*)buffer3,
- (tSize)strlen(buffer3));
- fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
-
- if (hdfsFlush(fs, appendFile)) {
- fprintf(stderr, "Failed to 'flush' %s\n", appendPath);
- exit(-1);
- }
- fprintf(stderr, "Flushed %s successfully!\n", appendPath);
-
- hdfsCloseFile(fs, appendFile);
-
- // RE-OPEN
- appendFile = hdfsOpenFile(fs, appendPath, O_WRONLY|O_APPEND, 0, 0, 0);
- if(!appendFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", appendPath);
- exit(-1);
- }
- fprintf(stderr, "Opened %s for writing successfully...\n", appendPath);
-
- buffer3 = " World";
- num_written_bytes = hdfsWrite(fs, appendFile, (void*)buffer3,
- (tSize)(strlen(buffer3) + 1));
- fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
-
- if (hdfsFlush(fs, appendFile)) {
- fprintf(stderr, "Failed to 'flush' %s\n", appendPath);
- exit(-1);
- }
- fprintf(stderr, "Flushed %s successfully!\n", appendPath);
-
- hdfsCloseFile(fs, appendFile);
-
- // CHECK size
- finfo = hdfsGetPathInfo(fs, appendPath);
- fprintf(stderr, "fileinfo->mSize: == total %s\n", ((result = (finfo->mSize == (tOffset)(strlen("Hello, World") + 1))) == 1 ? "Success!" : "Failed!"));
- totalResult += (result ? 0 : 1);
-
- // READ and check data
- readFile = hdfsOpenFile(fs, appendPath, O_RDONLY, 0, 0, 0);
- if (!readFile) {
- fprintf(stderr, "Failed to open %s for reading!\n", appendPath);
- exit(-1);
- }
-
- num_read_bytes = hdfsRead(fs, readFile, (void*)rdbuffer, sizeof(rdbuffer));
- fprintf(stderr, "Read following %d bytes:\n%s\n",
- num_read_bytes, rdbuffer);
-
- fprintf(stderr, "read == Hello, World %s\n", ((result = (strcmp(rdbuffer, "Hello, World"))) == 0 ? "Success!" : "Failed!"));
-
- hdfsCloseFile(fs, readFile);
-
- // DONE test appends
- }
-
-
- totalResult += (hdfsDisconnect(fs) != 0);
-
- {
- //
- // Now test as connecting as a specific user
- // This is only meant to test that we connected as that user, not to test
- // the actual fs user capabilities. Thus just create a file and read
- // the owner is correct.
-
- fs = hdfsConnectAsUserNewInstance("default", 0, tuser);
- if(!fs) {
- fprintf(stderr, "Oops! Failed to connect to hdfs as user %s!\n",tuser);
- exit(-1);
- }
-
- userFile = hdfsOpenFile(fs, userPath, O_WRONLY|O_CREAT, 0, 0, 0);
- if(!userFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", userPath);
- exit(-1);
- }
- fprintf(stderr, "Opened %s for writing successfully...\n", userPath);
-
- num_written_bytes = hdfsWrite(fs, userFile, (void*)fileContents,
- (tSize)(strlen(fileContents)+1));
- fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
-
- if (hdfsFlush(fs, userFile)) {
- fprintf(stderr, "Failed to 'flush' %s\n", userPath);
- exit(-1);
- }
- fprintf(stderr, "Flushed %s successfully!\n", userPath);
-
- hdfsCloseFile(fs, userFile);
-
- finfo = hdfsGetPathInfo(fs, userPath);
- fprintf(stderr, "hdfs new file user is correct: %s\n", ((result = (strcmp(finfo->mOwner, tuser))) != 0 ? "Failed!" : "Success!"));
- totalResult += result;
- }
-
- totalResult += (hdfsDisconnect(fs) != 0);
-
- if (totalResult != 0) {
- return -1;
- } else {
- return 0;
- }
-}
-
-/**
- * vim: ts=4: sw=4: et:
- */
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_read.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_read.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_read.c
deleted file mode 100644
index 6e44741..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_read.c
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "hdfs.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-int main(int argc, char **argv) {
- hdfsFS fs;
- const char *rfile = argv[1];
- tSize bufferSize = strtoul(argv[3], NULL, 10);
- hdfsFile readFile;
- char* buffer;
- tSize curSize;
-
- if (argc != 4) {
- fprintf(stderr, "Usage: hdfs_read <filename> <filesize> <buffersize>\n");
- exit(-1);
- }
-
- fs = hdfsConnect("default", 0);
- if (!fs) {
- fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
- exit(-1);
- }
-
- readFile = hdfsOpenFile(fs, rfile, O_RDONLY, bufferSize, 0, 0);
- if (!readFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", rfile);
- exit(-2);
- }
-
- // data to be written to the file
- buffer = malloc(sizeof(char) * bufferSize);
- if(buffer == NULL) {
- return -2;
- }
-
- // read from the file
- curSize = bufferSize;
- for (; curSize == bufferSize;) {
- curSize = hdfsRead(fs, readFile, (void*)buffer, curSize);
- }
-
-
- free(buffer);
- hdfsCloseFile(fs, readFile);
- hdfsDisconnect(fs);
-
- return 0;
-}
-
-/**
- * vim: ts=4: sw=4: et:
- */
-
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_write.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_write.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_write.c
deleted file mode 100644
index 42b3df7..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_write.c
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "hdfs.h"
-
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/types.h>
-
-int main(int argc, char **argv) {
- hdfsFS fs;
- const char *writeFileName = argv[1];
- off_t fileTotalSize = strtoul(argv[2], NULL, 10);
- long long tmpBufferSize = strtoul(argv[3], NULL, 10);
- tSize bufferSize;
- hdfsFile writeFile;
- char* buffer;
- int i;
- off_t nrRemaining;
- tSize curSize;
- tSize written;
-
- if (argc != 4) {
- fprintf(stderr, "Usage: hdfs_write <filename> <filesize> <buffersize>\n");
- exit(-1);
- }
-
- fs = hdfsConnect("default", 0);
- if (!fs) {
- fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
- exit(-1);
- }
-
- // sanity check
- if(fileTotalSize == ULONG_MAX && errno == ERANGE) {
- fprintf(stderr, "invalid file size %s - must be <= %lu\n", argv[2], ULONG_MAX);
- exit(-3);
- }
-
- // currently libhdfs writes are of tSize which is int32
- if(tmpBufferSize > INT_MAX) {
- fprintf(stderr, "invalid buffer size libhdfs API write chunks must be <= %d\n",INT_MAX);
- exit(-3);
- }
-
- bufferSize = (tSize)tmpBufferSize;
-
- writeFile = hdfsOpenFile(fs, writeFileName, O_WRONLY, bufferSize, 0, 0);
- if (!writeFile) {
- fprintf(stderr, "Failed to open %s for writing!\n", writeFileName);
- exit(-2);
- }
-
- // data to be written to the file
- buffer = malloc(sizeof(char) * bufferSize);
- if(buffer == NULL) {
- fprintf(stderr, "Could not allocate buffer of size %d\n", bufferSize);
- return -2;
- }
- for (i=0; i < bufferSize; ++i) {
- buffer[i] = 'a' + (i%26);
- }
-
- // write to the file
- for (nrRemaining = fileTotalSize; nrRemaining > 0; nrRemaining -= bufferSize ) {
- curSize = ( bufferSize < nrRemaining ) ? bufferSize : (tSize)nrRemaining;
- if ((written = hdfsWrite(fs, writeFile, (void*)buffer, curSize)) != curSize) {
- fprintf(stderr, "ERROR: hdfsWrite returned an error on write: %d\n", written);
- exit(-3);
- }
- }
-
- free(buffer);
- hdfsCloseFile(fs, writeFile);
- hdfsDisconnect(fs);
-
- return 0;
-}
-
-/**
- * vim: ts=4: sw=4: et:
- */
-
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_zerocopy.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_zerocopy.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_zerocopy.c
deleted file mode 100644
index 92941cf..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/test/test_libhdfs_zerocopy.c
+++ /dev/null
@@ -1,280 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "expect.h"
-#include "hdfs.h"
-#include "native_mini_dfs.h"
-#include "platform.h"
-
-#include <errno.h>
-#include <inttypes.h>
-#include <unistd.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-
-#define TO_STR_HELPER(X) #X
-#define TO_STR(X) TO_STR_HELPER(X)
-
-#define TEST_FILE_NAME_LENGTH 128
-#define TEST_ZEROCOPY_FULL_BLOCK_SIZE 4096
-#define TEST_ZEROCOPY_LAST_BLOCK_SIZE 3215
-#define TEST_ZEROCOPY_NUM_BLOCKS 6
-#define SMALL_READ_LEN 16
-#define TEST_ZEROCOPY_FILE_LEN \
- (((TEST_ZEROCOPY_NUM_BLOCKS - 1) * TEST_ZEROCOPY_FULL_BLOCK_SIZE) + \
- TEST_ZEROCOPY_LAST_BLOCK_SIZE)
-
-#define ZC_BUF_LEN 32768
-
-static uint8_t *getZeroCopyBlockData(int blockIdx)
-{
- uint8_t *buf = malloc(TEST_ZEROCOPY_FULL_BLOCK_SIZE);
- int i;
- if (!buf) {
- fprintf(stderr, "malloc(%d) failed\n", TEST_ZEROCOPY_FULL_BLOCK_SIZE);
- exit(1);
- }
- for (i = 0; i < TEST_ZEROCOPY_FULL_BLOCK_SIZE; i++) {
- buf[i] = (uint8_t)(blockIdx + (i % 17));
- }
- return buf;
-}
-
-static int getZeroCopyBlockLen(int blockIdx)
-{
- if (blockIdx >= TEST_ZEROCOPY_NUM_BLOCKS) {
- return 0;
- } else if (blockIdx == (TEST_ZEROCOPY_NUM_BLOCKS - 1)) {
- return TEST_ZEROCOPY_LAST_BLOCK_SIZE;
- } else {
- return TEST_ZEROCOPY_FULL_BLOCK_SIZE;
- }
-}
-
-static int doTestZeroCopyReads(hdfsFS fs, const char *fileName)
-{
- hdfsFile file = NULL;
- struct hadoopRzOptions *opts = NULL;
- struct hadoopRzBuffer *buffer = NULL;
- uint8_t *block;
-
- file = hdfsOpenFile(fs, fileName, O_RDONLY, 0, 0, 0);
- EXPECT_NONNULL(file);
- opts = hadoopRzOptionsAlloc();
- EXPECT_NONNULL(opts);
- EXPECT_ZERO(hadoopRzOptionsSetSkipChecksum(opts, 1));
- /* haven't read anything yet */
- EXPECT_ZERO(expectFileStats(file, 0LL, 0LL, 0LL, 0LL));
- block = getZeroCopyBlockData(0);
- EXPECT_NONNULL(block);
- /* first read is half of a block. */
- buffer = hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2);
- EXPECT_NONNULL(buffer);
- EXPECT_INT_EQ(TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2,
- hadoopRzBufferLength(buffer));
- EXPECT_ZERO(memcmp(hadoopRzBufferGet(buffer), block,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2));
- hadoopRzBufferFree(file, buffer);
- /* read the next half of the block */
- buffer = hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2);
- EXPECT_NONNULL(buffer);
- EXPECT_INT_EQ(TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2,
- hadoopRzBufferLength(buffer));
- EXPECT_ZERO(memcmp(hadoopRzBufferGet(buffer),
- block + (TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2),
- TEST_ZEROCOPY_FULL_BLOCK_SIZE / 2));
- hadoopRzBufferFree(file, buffer);
- free(block);
- EXPECT_ZERO(expectFileStats(file, TEST_ZEROCOPY_FULL_BLOCK_SIZE,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE));
- /* Now let's read just a few bytes. */
- buffer = hadoopReadZero(file, opts, SMALL_READ_LEN);
- EXPECT_NONNULL(buffer);
- EXPECT_INT_EQ(SMALL_READ_LEN, hadoopRzBufferLength(buffer));
- block = getZeroCopyBlockData(1);
- EXPECT_NONNULL(block);
- EXPECT_ZERO(memcmp(block, hadoopRzBufferGet(buffer), SMALL_READ_LEN));
- hadoopRzBufferFree(file, buffer);
- EXPECT_INT64_EQ(
- (int64_t)TEST_ZEROCOPY_FULL_BLOCK_SIZE + (int64_t)SMALL_READ_LEN,
- hdfsTell(fs, file));
- EXPECT_ZERO(expectFileStats(file,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN));
-
- /* Clear 'skip checksums' and test that we can't do zero-copy reads any
- * more. Since there is no ByteBufferPool set, we should fail with
- * EPROTONOSUPPORT.
- */
- EXPECT_ZERO(hadoopRzOptionsSetSkipChecksum(opts, 0));
- EXPECT_NULL(hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE));
- EXPECT_INT_EQ(EPROTONOSUPPORT, errno);
-
- /* Verify that setting a NULL ByteBufferPool class works. */
- EXPECT_ZERO(hadoopRzOptionsSetByteBufferPool(opts, NULL));
- EXPECT_ZERO(hadoopRzOptionsSetSkipChecksum(opts, 0));
- EXPECT_NULL(hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE));
- EXPECT_INT_EQ(EPROTONOSUPPORT, errno);
-
- /* Now set a ByteBufferPool and try again. It should succeed this time. */
- EXPECT_ZERO(hadoopRzOptionsSetByteBufferPool(opts,
- ELASTIC_BYTE_BUFFER_POOL_CLASS));
- buffer = hadoopReadZero(file, opts, TEST_ZEROCOPY_FULL_BLOCK_SIZE);
- EXPECT_NONNULL(buffer);
- EXPECT_INT_EQ(TEST_ZEROCOPY_FULL_BLOCK_SIZE, hadoopRzBufferLength(buffer));
- EXPECT_ZERO(expectFileStats(file,
- (2 * TEST_ZEROCOPY_FULL_BLOCK_SIZE) + SMALL_READ_LEN,
- (2 * TEST_ZEROCOPY_FULL_BLOCK_SIZE) + SMALL_READ_LEN,
- (2 * TEST_ZEROCOPY_FULL_BLOCK_SIZE) + SMALL_READ_LEN,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE + SMALL_READ_LEN));
- EXPECT_ZERO(memcmp(block + SMALL_READ_LEN, hadoopRzBufferGet(buffer),
- TEST_ZEROCOPY_FULL_BLOCK_SIZE - SMALL_READ_LEN));
- free(block);
- block = getZeroCopyBlockData(2);
- EXPECT_NONNULL(block);
- EXPECT_ZERO(memcmp(block, (uint8_t*)hadoopRzBufferGet(buffer) +
- (TEST_ZEROCOPY_FULL_BLOCK_SIZE - SMALL_READ_LEN), SMALL_READ_LEN));
- hadoopRzBufferFree(file, buffer);
-
- /* Check the result of a zero-length read. */
- buffer = hadoopReadZero(file, opts, 0);
- EXPECT_NONNULL(buffer);
- EXPECT_NONNULL(hadoopRzBufferGet(buffer));
- EXPECT_INT_EQ(0, hadoopRzBufferLength(buffer));
- hadoopRzBufferFree(file, buffer);
-
- /* Check the result of reading past EOF */
- EXPECT_INT_EQ(0, hdfsSeek(fs, file, TEST_ZEROCOPY_FILE_LEN));
- buffer = hadoopReadZero(file, opts, 1);
- EXPECT_NONNULL(buffer);
- EXPECT_NULL(hadoopRzBufferGet(buffer));
- hadoopRzBufferFree(file, buffer);
-
- /* Cleanup */
- free(block);
- hadoopRzOptionsFree(opts);
- EXPECT_ZERO(hdfsCloseFile(fs, file));
- return 0;
-}
-
-static int createZeroCopyTestFile(hdfsFS fs, char *testFileName,
- size_t testFileNameLen)
-{
- int blockIdx, blockLen;
- hdfsFile file;
- uint8_t *data;
-
- snprintf(testFileName, testFileNameLen, "/zeroCopyTestFile.%d.%d",
- getpid(), rand());
- file = hdfsOpenFile(fs, testFileName, O_WRONLY, 0, 1,
- TEST_ZEROCOPY_FULL_BLOCK_SIZE);
- EXPECT_NONNULL(file);
- for (blockIdx = 0; blockIdx < TEST_ZEROCOPY_NUM_BLOCKS; blockIdx++) {
- blockLen = getZeroCopyBlockLen(blockIdx);
- data = getZeroCopyBlockData(blockIdx);
- EXPECT_NONNULL(data);
- EXPECT_INT_EQ(blockLen, hdfsWrite(fs, file, data, blockLen));
- }
- EXPECT_ZERO(hdfsCloseFile(fs, file));
- return 0;
-}
-
-static int nmdConfigureHdfsBuilder(struct NativeMiniDfsCluster *cl,
- struct hdfsBuilder *bld) {
- int ret;
- tPort port;
- const char *domainSocket;
-
- hdfsBuilderSetNameNode(bld, "localhost");
- port = (tPort) nmdGetNameNodePort(cl);
- if (port < 0) {
- fprintf(stderr, "nmdGetNameNodePort failed with error %d\n", -port);
- return EIO;
- }
- hdfsBuilderSetNameNodePort(bld, port);
-
- domainSocket = hdfsGetDomainSocketPath(cl);
-
- if (domainSocket) {
- ret = hdfsBuilderConfSetStr(bld, "dfs.client.read.shortcircuit", "true");
- if (ret) {
- return ret;
- }
- ret = hdfsBuilderConfSetStr(bld, "dfs.domain.socket.path",
- domainSocket);
- if (ret) {
- return ret;
- }
- }
- return 0;
-}
-
-
-/**
- * Test that we can write a file with libhdfs and then read it back
- */
-int main(void)
-{
- int port;
- struct NativeMiniDfsConf conf = {
- 1, /* doFormat */
- 0, /* webhdfsEnabled */
- 0, /* namenodeHttpPort */
- 1, /* configureShortCircuit */
- };
- char testFileName[TEST_FILE_NAME_LENGTH];
- hdfsFS fs;
- struct NativeMiniDfsCluster* cl;
- struct hdfsBuilder *bld;
-
- cl = nmdCreate(&conf);
- EXPECT_NONNULL(cl);
- EXPECT_ZERO(nmdWaitClusterUp(cl));
- port = nmdGetNameNodePort(cl);
- if (port < 0) {
- fprintf(stderr, "TEST_ERROR: test_zerocopy: "
- "nmdGetNameNodePort returned error %d\n", port);
- return EXIT_FAILURE;
- }
- bld = hdfsNewBuilder();
- EXPECT_NONNULL(bld);
- EXPECT_ZERO(nmdConfigureHdfsBuilder(cl, bld));
- hdfsBuilderSetForceNewInstance(bld);
- hdfsBuilderConfSetStr(bld, "dfs.block.size",
- TO_STR(TEST_ZEROCOPY_FULL_BLOCK_SIZE));
- /* ensure that we'll always get our mmaps */
- hdfsBuilderConfSetStr(bld, "dfs.client.read.shortcircuit.skip.checksum",
- "true");
- fs = hdfsBuilderConnect(bld);
- EXPECT_NONNULL(fs);
- EXPECT_ZERO(createZeroCopyTestFile(fs, testFileName,
- TEST_FILE_NAME_LENGTH));
- EXPECT_ZERO(doTestZeroCopyReads(fs, testFileName));
- EXPECT_ZERO(hdfsDisconnect(fs));
- EXPECT_ZERO(nmdShutdown(cl));
- nmdFree(cl);
- fprintf(stderr, "TEST_SUCCESS\n");
- return EXIT_SUCCESS;
-}
[23/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_json_parser.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_json_parser.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_json_parser.c
new file mode 100644
index 0000000..178fb9d
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_json_parser.c
@@ -0,0 +1,654 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "exception.h"
+#include "hdfs.h" /* for hdfsFileInfo */
+#include "hdfs_json_parser.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <jansson.h>
+
+static const char * const temporaryRedirectCode = "307 TEMPORARY_REDIRECT";
+static const char * const twoHundredOKCode = "200 OK";
+static const char * const twoHundredOneCreatedCode = "201 Created";
+static const char * const httpHeaderString = "HTTP/1.1";
+
+/**
+ * Exception information after calling JSON operations
+ */
+struct jsonException {
+ const char *exception;
+ const char *javaClassName;
+ const char *message;
+};
+
+/** Print out the JSON exception information */
+static int printJsonExceptionV(struct jsonException *exc, int noPrintFlags,
+ const char *fmt, va_list ap)
+{
+ char *javaClassName = NULL;
+ int excErrno = EINTERNAL, shouldPrint = 0;
+ if (!exc) {
+ fprintf(stderr, "printJsonExceptionV: the jsonException is NULL\n");
+ return EINTERNAL;
+ }
+ javaClassName = strdup(exc->javaClassName);
+ if (!javaClassName) {
+ fprintf(stderr, "printJsonExceptionV: internal out of memory error\n");
+ return EINTERNAL;
+ }
+ getExceptionInfo(javaClassName, noPrintFlags, &excErrno, &shouldPrint);
+ free(javaClassName);
+
+ if (shouldPrint) {
+ vfprintf(stderr, fmt, ap);
+ fprintf(stderr, " error:\n");
+ fprintf(stderr, "Exception: %s\nJavaClassName: %s\nMessage: %s\n",
+ exc->exception, exc->javaClassName, exc->message);
+ }
+
+ free(exc);
+ return excErrno;
+}
+
+/**
+ * Print out JSON exception information.
+ *
+ * @param exc The exception information to print and free
+ * @param noPrintFlags Flags which determine which exceptions we should NOT
+ * print.
+ * @param fmt Printf-style format list
+ * @param ... Printf-style varargs
+ *
+ * @return The POSIX error number associated with the exception
+ * object.
+ */
+static int printJsonException(struct jsonException *exc, int noPrintFlags,
+ const char *fmt, ...)
+{
+ va_list ap;
+ int ret = 0;
+
+ va_start(ap, fmt);
+ ret = printJsonExceptionV(exc, noPrintFlags, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+/** Parse the exception information from JSON */
+static struct jsonException *parseJsonException(json_t *jobj)
+{
+ const char *key = NULL;
+ json_t *value = NULL;
+ struct jsonException *exception = NULL;
+ void *iter = NULL;
+
+ exception = calloc(1, sizeof(*exception));
+ if (!exception) {
+ return NULL;
+ }
+
+ iter = json_object_iter(jobj);
+ while (iter) {
+ key = json_object_iter_key(iter);
+ value = json_object_iter_value(iter);
+
+ if (!strcmp(key, "exception")) {
+ exception->exception = json_string_value(value);
+ } else if (!strcmp(key, "javaClassName")) {
+ exception->javaClassName = json_string_value(value);
+ } else if (!strcmp(key, "message")) {
+ exception->message = json_string_value(value);
+ }
+
+ iter = json_object_iter_next(jobj, iter);
+ }
+ return exception;
+}
+
+/**
+ * Parse the exception information which is presented in JSON
+ *
+ * @param content Exception information in JSON
+ * @return jsonException for printing out
+ */
+static struct jsonException *parseException(const char *content)
+{
+ json_error_t error;
+ size_t flags = 0;
+ const char *key = NULL;
+ json_t *value;
+ json_t *jobj;
+ struct jsonException *exception = NULL;
+
+ if (!content) {
+ return NULL;
+ }
+ jobj = json_loads(content, flags, &error);
+ if (!jobj) {
+ fprintf(stderr, "JSon parsing error: on line %d: %s\n",
+ error.line, error.text);
+ return NULL;
+ }
+ void *iter = json_object_iter(jobj);
+ while(iter) {
+ key = json_object_iter_key(iter);
+ value = json_object_iter_value(iter);
+
+ if (!strcmp(key, "RemoteException") &&
+ json_typeof(value) == JSON_OBJECT) {
+ exception = parseJsonException(value);
+ break;
+ }
+ iter = json_object_iter_next(jobj, iter);
+ }
+
+ json_decref(jobj);
+ return exception;
+}
+
+/**
+ * Parse the response information which uses TRUE/FALSE
+ * to indicate whether the operation succeeded
+ *
+ * @param response Response information
+ * @return 0 to indicate success
+ */
+static int parseBoolean(const char *response)
+{
+ json_t *root, *value;
+ json_error_t error;
+ size_t flags = 0;
+ int result = 0;
+
+ root = json_loads(response, flags, &error);
+ if (!root) {
+ fprintf(stderr, "JSon parsing error: on line %d: %s\n",
+ error.line, error.text);
+ return EIO;
+ }
+ void *iter = json_object_iter(root);
+ value = json_object_iter_value(iter);
+ if (json_typeof(value) == JSON_TRUE) {
+ result = 0;
+ } else {
+ result = EIO; // FALSE means error in remote NN/DN
+ }
+ json_decref(root);
+ return result;
+}
+
+int parseMKDIR(const char *response)
+{
+ return parseBoolean(response);
+}
+
+int parseRENAME(const char *response)
+{
+ return parseBoolean(response);
+}
+
+int parseDELETE(const char *response)
+{
+ return parseBoolean(response);
+}
+
+int parseSETREPLICATION(const char *response)
+{
+ return parseBoolean(response);
+}
+
+/**
+ * Check the header of response to see if it's 200 OK
+ *
+ * @param header Header information for checking
+ * @param content Stores exception information if there are errors
+ * @param operation Indicate the operation for exception printing
+ * @return 0 for success
+ */
+static int checkHeader(const char *header, const char *content,
+ const char *operation)
+{
+ char *result = NULL;
+ const char delims[] = ":";
+ char *savepter;
+ int ret = 0;
+
+ if (!header || strncmp(header, "HTTP/", strlen("HTTP/"))) {
+ return EINVAL;
+ }
+ if (!(strstr(header, twoHundredOKCode)) ||
+ !(result = strstr(header, "Content-Length"))) {
+ struct jsonException *exc = parseException(content);
+ if (exc) {
+ ret = printJsonException(exc, PRINT_EXC_ALL,
+ "Calling WEBHDFS (%s)", operation);
+ } else {
+ ret = EIO;
+ }
+ return ret;
+ }
+ result = strtok_r(result, delims, &savepter);
+ result = strtok_r(NULL, delims, &savepter);
+ while (isspace(*result)) {
+ result++;
+ }
+ // Content-Length should be equal to 0,
+ // and the string should be "0\r\nServer"
+ if (strncmp(result, "0\r\n", 3)) {
+ ret = EIO;
+ }
+ return ret;
+}
+
+int parseCHMOD(const char *header, const char *content)
+{
+ return checkHeader(header, content, "CHMOD");
+}
+
+int parseCHOWN(const char *header, const char *content)
+{
+ return checkHeader(header, content, "CHOWN");
+}
+
+int parseUTIMES(const char *header, const char *content)
+{
+ return checkHeader(header, content, "SETTIMES");
+}
+
+/**
+ * Check if the header contains correct information
+ * ("307 TEMPORARY_REDIRECT" and "Location")
+ *
+ * @param header Header for parsing
+ * @param content Contains exception information
+ * if the remote operation failed
+ * @param operation Specify the remote operation when printing out exception
+ * @return 0 for success
+ */
+static int checkRedirect(const char *header,
+ const char *content, const char *operation)
+{
+ const char *locTag = "Location";
+ int ret = 0, offset = 0;
+
+ // The header must start with "HTTP/1.1"
+ if (!header || strncmp(header, httpHeaderString,
+ strlen(httpHeaderString))) {
+ return EINVAL;
+ }
+
+ offset += strlen(httpHeaderString);
+ while (isspace(header[offset])) {
+ offset++;
+ }
+ // Looking for "307 TEMPORARY_REDIRECT" in header
+ if (strncmp(header + offset, temporaryRedirectCode,
+ strlen(temporaryRedirectCode))) {
+ // Process possible exception information
+ struct jsonException *exc = parseException(content);
+ if (exc) {
+ ret = printJsonException(exc, PRINT_EXC_ALL,
+ "Calling WEBHDFS (%s)", operation);
+ } else {
+ ret = EIO;
+ }
+ return ret;
+ }
+ // Here we just simply check if header contains "Location" tag,
+ // detailed processing is in parseDnLoc
+ if (!(strstr(header, locTag))) {
+ ret = EIO;
+ }
+ return ret;
+}
+
+int parseNnWRITE(const char *header, const char *content)
+{
+ return checkRedirect(header, content, "Write(NameNode)");
+}
+
+int parseNnAPPEND(const char *header, const char *content)
+{
+ return checkRedirect(header, content, "Append(NameNode)");
+}
+
+/** 0 for success , -1 for out of range, other values for error */
+int parseOPEN(const char *header, const char *content)
+{
+ int ret = 0, offset = 0;
+
+ if (!header || strncmp(header, httpHeaderString,
+ strlen(httpHeaderString))) {
+ return EINVAL;
+ }
+
+ offset += strlen(httpHeaderString);
+ while (isspace(header[offset])) {
+ offset++;
+ }
+ if (strncmp(header + offset, temporaryRedirectCode,
+ strlen(temporaryRedirectCode)) ||
+ !strstr(header, twoHundredOKCode)) {
+ struct jsonException *exc = parseException(content);
+ if (exc) {
+ // If the exception is an IOException and it is because
+ // the offset is out of the range, do not print out the exception
+ if (!strcasecmp(exc->exception, "IOException") &&
+ strstr(exc->message, "out of the range")) {
+ ret = -1;
+ } else {
+ ret = printJsonException(exc, PRINT_EXC_ALL,
+ "Calling WEBHDFS (OPEN)");
+ }
+ } else {
+ ret = EIO;
+ }
+ }
+ return ret;
+}
+
+int parseDnLoc(char *content, char **dn)
+{
+ char *url = NULL, *dnLocation = NULL, *savepter, *tempContent;
+ const char *prefix = "Location: http://";
+ const char *prefixToRemove = "Location: ";
+ const char *delims = "\r\n";
+
+ tempContent = strdup(content);
+ if (!tempContent) {
+ return ENOMEM;
+ }
+
+ dnLocation = strtok_r(tempContent, delims, &savepter);
+ while (dnLocation && strncmp(dnLocation, "Location:",
+ strlen("Location:"))) {
+ dnLocation = strtok_r(NULL, delims, &savepter);
+ }
+ if (!dnLocation) {
+ return EIO;
+ }
+
+ while (isspace(*dnLocation)) {
+ dnLocation++;
+ }
+ if (strncmp(dnLocation, prefix, strlen(prefix))) {
+ return EIO;
+ }
+ url = strdup(dnLocation + strlen(prefixToRemove));
+ if (!url) {
+ return ENOMEM;
+ }
+ *dn = url;
+ return 0;
+}
+
+int parseDnWRITE(const char *header, const char *content)
+{
+ int ret = 0;
+ if (header == NULL || header[0] == '\0' ||
+ strncmp(header, "HTTP/", strlen("HTTP/"))) {
+ return EINVAL;
+ }
+ if (!(strstr(header, twoHundredOneCreatedCode))) {
+ struct jsonException *exc = parseException(content);
+ if (exc) {
+ ret = printJsonException(exc, PRINT_EXC_ALL,
+ "Calling WEBHDFS (WRITE(DataNode))");
+ } else {
+ ret = EIO;
+ }
+ }
+ return ret;
+}
+
+int parseDnAPPEND(const char *header, const char *content)
+{
+ int ret = 0;
+
+ if (header == NULL || header[0] == '\0' ||
+ strncmp(header, "HTTP/", strlen("HTTP/"))) {
+ return EINVAL;
+ }
+ if (!(strstr(header, twoHundredOKCode))) {
+ struct jsonException *exc = parseException(content);
+ if (exc) {
+ ret = printJsonException(exc, PRINT_EXC_ALL,
+ "Calling WEBHDFS (APPEND(DataNode))");
+ } else {
+ ret = EIO;
+ }
+ }
+ return ret;
+}
+
+/**
+ * Retrieve file status from the JSON object
+ *
+ * @param jobj JSON object for parsing, which contains
+ * file status information
+ * @param fileStat hdfsFileInfo handle to hold file status information
+ * @return 0 on success
+ */
+static int parseJsonForFileStatus(json_t *jobj, hdfsFileInfo *fileStat)
+{
+ const char *key, *tempstr;
+ json_t *value;
+ void *iter = NULL;
+
+ iter = json_object_iter(jobj);
+ while (iter) {
+ key = json_object_iter_key(iter);
+ value = json_object_iter_value(iter);
+
+ if (!strcmp(key, "accessTime")) {
+ // json field contains time in milliseconds,
+ // hdfsFileInfo is counted in seconds
+ fileStat->mLastAccess = json_integer_value(value) / 1000;
+ } else if (!strcmp(key, "blockSize")) {
+ fileStat->mBlockSize = json_integer_value(value);
+ } else if (!strcmp(key, "length")) {
+ fileStat->mSize = json_integer_value(value);
+ } else if (!strcmp(key, "modificationTime")) {
+ fileStat->mLastMod = json_integer_value(value) / 1000;
+ } else if (!strcmp(key, "replication")) {
+ fileStat->mReplication = json_integer_value(value);
+ } else if (!strcmp(key, "group")) {
+ fileStat->mGroup = strdup(json_string_value(value));
+ if (!fileStat->mGroup) {
+ return ENOMEM;
+ }
+ } else if (!strcmp(key, "owner")) {
+ fileStat->mOwner = strdup(json_string_value(value));
+ if (!fileStat->mOwner) {
+ return ENOMEM;
+ }
+ } else if (!strcmp(key, "pathSuffix")) {
+ fileStat->mName = strdup(json_string_value(value));
+ if (!fileStat->mName) {
+ return ENOMEM;
+ }
+ } else if (!strcmp(key, "permission")) {
+ tempstr = json_string_value(value);
+ fileStat->mPermissions = (short) strtol(tempstr, NULL, 8);
+ } else if (!strcmp(key, "type")) {
+ tempstr = json_string_value(value);
+ if (!strcmp(tempstr, "DIRECTORY")) {
+ fileStat->mKind = kObjectKindDirectory;
+ } else {
+ fileStat->mKind = kObjectKindFile;
+ }
+ }
+ // Go to the next key-value pair in the json object
+ iter = json_object_iter_next(jobj, iter);
+ }
+ return 0;
+}
+
+int parseGFS(const char *response, hdfsFileInfo *fileStat, int printError)
+{
+ int ret = 0, printFlag;
+ json_error_t error;
+ size_t flags = 0;
+ json_t *jobj, *value;
+ const char *key;
+ void *iter = NULL;
+
+ if (!response || !fileStat) {
+ return EIO;
+ }
+ jobj = json_loads(response, flags, &error);
+ if (!jobj) {
+ fprintf(stderr, "error while parsing json: on line %d: %s\n",
+ error.line, error.text);
+ return EIO;
+ }
+ iter = json_object_iter(jobj);
+ key = json_object_iter_key(iter);
+ value = json_object_iter_value(iter);
+ if (json_typeof(value) == JSON_OBJECT) {
+ if (!strcmp(key, "RemoteException")) {
+ struct jsonException *exception = parseJsonException(value);
+ if (exception) {
+ if (printError) {
+ printFlag = PRINT_EXC_ALL;
+ } else {
+ printFlag = NOPRINT_EXC_FILE_NOT_FOUND |
+ NOPRINT_EXC_ACCESS_CONTROL |
+ NOPRINT_EXC_PARENT_NOT_DIRECTORY;
+ }
+ ret = printJsonException(exception, printFlag,
+ "Calling WEBHDFS GETFILESTATUS");
+ } else {
+ ret = EIO;
+ }
+ } else if (!strcmp(key, "FileStatus")) {
+ ret = parseJsonForFileStatus(value, fileStat);
+ } else {
+ ret = EIO;
+ }
+
+ } else {
+ ret = EIO;
+ }
+
+ json_decref(jobj);
+ return ret;
+}
+
+/**
+ * Parse the JSON array. Called to parse the result of
+ * the LISTSTATUS operation. Thus each element of the JSON array is
+ * a JSON object with the information of a file entry contained
+ * in the folder.
+ *
+ * @param jobj The JSON array to be parsed
+ * @param fileStat The hdfsFileInfo handle used to
+ * store a group of file information
+ * @param numEntries Capture the number of files in the folder
+ * @return 0 for success
+ */
+static int parseJsonArrayForFileStatuses(json_t *jobj, hdfsFileInfo **fileStat,
+ int *numEntries)
+{
+ json_t *jvalue = NULL;
+ int i = 0, ret = 0, arraylen = 0;
+ hdfsFileInfo *fileInfo = NULL;
+
+ arraylen = (int) json_array_size(jobj);
+ if (arraylen > 0) {
+ fileInfo = calloc(arraylen, sizeof(hdfsFileInfo));
+ if (!fileInfo) {
+ return ENOMEM;
+ }
+ }
+ for (i = 0; i < arraylen; i++) {
+ //Getting the array element at position i
+ jvalue = json_array_get(jobj, i);
+ if (json_is_object(jvalue)) {
+ ret = parseJsonForFileStatus(jvalue, &fileInfo[i]);
+ if (ret) {
+ goto done;
+ }
+ } else {
+ ret = EIO;
+ goto done;
+ }
+ }
+done:
+ if (ret) {
+ free(fileInfo);
+ } else {
+ *numEntries = arraylen;
+ *fileStat = fileInfo;
+ }
+ return ret;
+}
+
+int parseLS(const char *response, hdfsFileInfo **fileStats, int *numOfEntries)
+{
+ int ret = 0;
+ json_error_t error;
+ size_t flags = 0;
+ json_t *jobj, *value;
+ const char *key;
+ void *iter = NULL;
+
+ if (!response || response[0] == '\0' || !fileStats) {
+ return EIO;
+ }
+ jobj = json_loads(response, flags, &error);
+ if (!jobj) {
+ fprintf(stderr, "error while parsing json: on line %d: %s\n",
+ error.line, error.text);
+ return EIO;
+ }
+
+ iter = json_object_iter(jobj);
+ key = json_object_iter_key(iter);
+ value = json_object_iter_value(iter);
+ if (json_typeof(value) == JSON_OBJECT) {
+ if (!strcmp(key, "RemoteException")) {
+ struct jsonException *exception = parseJsonException(value);
+ if (exception) {
+ ret = printJsonException(exception, PRINT_EXC_ALL,
+ "Calling WEBHDFS GETFILESTATUS");
+ } else {
+ ret = EIO;
+ }
+ } else if (!strcmp(key, "FileStatuses")) {
+ iter = json_object_iter(value);
+ value = json_object_iter_value(iter);
+ if (json_is_array(value)) {
+ ret = parseJsonArrayForFileStatuses(value, fileStats,
+ numOfEntries);
+ } else {
+ ret = EIO;
+ }
+ } else {
+ ret = EIO;
+ }
+ } else {
+ ret = EIO;
+ }
+
+ json_decref(jobj);
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_json_parser.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_json_parser.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_json_parser.h
new file mode 100644
index 0000000..c5f2f9c
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_json_parser.h
@@ -0,0 +1,178 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+#ifndef _HDFS_JSON_PARSER_H_
+#define _HDFS_JSON_PARSER_H_
+
+/**
+ * Parse the response for MKDIR request. The response uses TRUE/FALSE
+ * to indicate whether the operation succeeded.
+ *
+ * @param response The response information to parse.
+ * @return 0 for success
+ */
+int parseMKDIR(const char *response);
+
+/**
+ * Parse the response for RENAME request. The response uses TRUE/FALSE
+ * to indicate whether the operation succeeded.
+ *
+ * @param response The response information to parse.
+ * @return 0 for success
+ */
+int parseRENAME(const char *response);
+
+/**
+ * Parse the response for DELETE request. The response uses TRUE/FALSE
+ * to indicate whether the operation succeeded.
+ *
+ * @param response The response information to parse.
+ * @return 0 for success
+ */
+int parseDELETE(const char *response);
+
+/**
+ * Parse the response for SETREPLICATION request. The response uses TRUE/FALSE
+ * to indicate whether the operation succeeded.
+ *
+ * @param response The response information to parse.
+ * @return 0 for success
+ */
+int parseSETREPLICATION(const char *response);
+
+/**
+ * Parse the response for OPEN (read) request. A successful operation
+ * will return "200 OK".
+ *
+ * @param response The response information for parsing
+ * @return 0 for success , -1 for out of range, other values for error
+ */
+int parseOPEN(const char *header, const char *content);
+
+/**
+ * Parse the response for WRITE (from NameNode) request.
+ * A successful operation should return "307 TEMPORARY_REDIRECT" in its header.
+ *
+ * @param header The header of the http response
+ * @param content If failing, the exception message
+ * sent from NameNode is stored in content
+ * @return 0 for success
+ */
+int parseNnWRITE(const char *header, const char *content);
+
+/**
+ * Parse the response for WRITE (from DataNode) request.
+ * A successful operation should return "201 Created" in its header.
+ *
+ * @param header The header of the http response
+ * @param content If failing, the exception message
+ * sent from DataNode is stored in content
+ * @return 0 for success
+ */
+int parseDnWRITE(const char *header, const char *content);
+
+/**
+ * Parse the response for APPEND (sent from NameNode) request.
+ * A successful operation should return "307 TEMPORARY_REDIRECT" in its header.
+ *
+ * @param header The header of the http response
+ * @param content If failing, the exception message
+ * sent from NameNode is stored in content
+ * @return 0 for success
+ */
+int parseNnAPPEND(const char *header, const char *content);
+
+/**
+ * Parse the response for APPEND (from DataNode) request.
+ * A successful operation should return "200 OK" in its header.
+ *
+ * @param header The header of the http response
+ * @param content If failing, the exception message
+ * sent from DataNode is stored in content
+ * @return 0 for success
+ */
+int parseDnAPPEND(const char *header, const char *content);
+
+/**
+ * Parse the response (from NameNode) to get the location information
+ * of the DataNode that should be contacted for the following write operation.
+ *
+ * @param content Content of the http header
+ * @param dn To store the location of the DataNode for writing
+ * @return 0 for success
+ */
+int parseDnLoc(char *content, char **dn) __attribute__ ((warn_unused_result));
+
+/**
+ * Parse the response for GETFILESTATUS operation.
+ *
+ * @param response Response to parse. Its detailed format is specified in
+ * "http://hadoop.apache.org/docs/stable/webhdfs.html#GETFILESTATUS"
+ * @param fileStat A hdfsFileInfo handle for holding file information
+ * @param printError Whether or not print out exception
+ * when file does not exist
+ * @return 0 for success, non-zero value to indicate error
+ */
+int parseGFS(const char *response, hdfsFileInfo *fileStat, int printError);
+
+/**
+ * Parse the response for LISTSTATUS operation.
+ *
+ * @param response Response to parse. Its detailed format is specified in
+ * "http://hadoop.apache.org/docs/r1.0.3/webhdfs.html#LISTSTATUS"
+ * @param fileStats Pointer pointing to a list of hdfsFileInfo handles
+ * holding file/dir information in the directory
+ * @param numEntries After parsing, the value of this parameter indicates
+ * the number of file entries.
+ * @return 0 for success, non-zero value to indicate error
+ */
+int parseLS(const char *response, hdfsFileInfo **fileStats, int *numOfEntries);
+
+/**
+ * Parse the response for CHOWN request.
+ * A successful operation should contains "200 OK" in its header,
+ * and the Content-Length should be 0.
+ *
+ * @param header The header of the http response
+ * @param content If failing, the exception message is stored in content
+ * @return 0 for success
+ */
+int parseCHOWN(const char *header, const char *content);
+
+/**
+ * Parse the response for CHMOD request.
+ * A successful operation should contains "200 OK" in its header,
+ * and the Content-Length should be 0.
+ *
+ * @param header The header of the http response
+ * @param content If failing, the exception message is stored in content
+ * @return 0 for success
+ */
+int parseCHMOD(const char *header, const char *content);
+
+/**
+ * Parse the response for SETTIMES request.
+ * A successful operation should contains "200 OK" in its header,
+ * and the Content-Length should be 0.
+ *
+ * @param header The header of the http response
+ * @param content If failing, the exception message is stored in content
+ * @return 0 for success
+ */
+int parseUTIMES(const char *header, const char *content);
+
+#endif //_HDFS_JSON_PARSER_H_
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_web.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_web.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_web.c
new file mode 100644
index 0000000..86b4faf
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/hdfs_web.c
@@ -0,0 +1,1538 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "exception.h"
+#include "hdfs.h"
+#include "hdfs_http_client.h"
+#include "hdfs_http_query.h"
+#include "hdfs_json_parser.h"
+#include "jni_helper.h"
+
+#define HADOOP_HDFS_CONF "org/apache/hadoop/hdfs/HdfsConfiguration"
+#define HADOOP_NAMENODE "org/apache/hadoop/hdfs/server/namenode/NameNode"
+#define JAVA_INETSOCKETADDRESS "java/net/InetSocketAddress"
+
+struct hdfsBuilder {
+ int forceNewInstance;
+ const char *nn;
+ tPort port;
+ const char *kerbTicketCachePath;
+ const char *userName;
+};
+
+/**
+ * The information required for accessing webhdfs,
+ * including the network address of the namenode and the user name
+ *
+ * Unlike the string in hdfsBuilder, the strings in this structure are
+ * dynamically allocated. This structure will not be freed until we disconnect
+ * from HDFS.
+ */
+struct hdfs_internal {
+ char *nn;
+ tPort port;
+ char *userName;
+
+ /**
+ * Working directory -- stored with a trailing slash.
+ */
+ char *workingDir;
+};
+
+/**
+ * The 'file-handle' to a file in hdfs.
+ */
+struct hdfsFile_internal {
+ struct webhdfsFileHandle* file;
+ enum hdfsStreamType type; /* INPUT or OUTPUT */
+ int flags; /* Flag indicate read/create/append etc. */
+ tOffset offset; /* Current offset position in the file */
+};
+
+/**
+ * Create, initialize and return a webhdfsBuffer
+ */
+static int initWebHdfsBuffer(struct webhdfsBuffer **webhdfsBuffer)
+{
+ int ret = 0;
+ struct webhdfsBuffer *buffer = calloc(1, sizeof(struct webhdfsBuffer));
+ if (!buffer) {
+ fprintf(stderr,
+ "ERROR: fail to allocate memory for webhdfsBuffer.\n");
+ return ENOMEM;
+ }
+ ret = pthread_mutex_init(&buffer->writeMutex, NULL);
+ if (ret) {
+ fprintf(stderr, "ERROR: fail in pthread_mutex_init for writeMutex "
+ "in initWebHdfsBuffer, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ goto done;
+ }
+ ret = pthread_cond_init(&buffer->newwrite_or_close, NULL);
+ if (ret) {
+ fprintf(stderr,
+ "ERROR: fail in pthread_cond_init for newwrite_or_close "
+ "in initWebHdfsBuffer, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ goto done;
+ }
+ ret = pthread_cond_init(&buffer->transfer_finish, NULL);
+ if (ret) {
+ fprintf(stderr,
+ "ERROR: fail in pthread_cond_init for transfer_finish "
+ "in initWebHdfsBuffer, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ goto done;
+ }
+
+done:
+ if (ret) {
+ free(buffer);
+ return ret;
+ }
+ *webhdfsBuffer = buffer;
+ return 0;
+}
+
+/**
+ * Reset the webhdfsBuffer. This is used in a block way
+ * when hdfsWrite is called with a new buffer to write.
+ * The writing thread in libcurl will be waken up to continue writing,
+ * and the caller of this function is blocked waiting for writing to finish.
+ *
+ * @param wb The handle of the webhdfsBuffer
+ * @param buffer The buffer provided by user to write
+ * @param length The length of bytes to write
+ * @return Updated webhdfsBuffer.
+ */
+static struct webhdfsBuffer *resetWebhdfsBuffer(struct webhdfsBuffer *wb,
+ const char *buffer, size_t length)
+{
+ if (buffer && length > 0) {
+ pthread_mutex_lock(&wb->writeMutex);
+ wb->wbuffer = buffer;
+ wb->offset = 0;
+ wb->remaining = length;
+ pthread_cond_signal(&wb->newwrite_or_close);
+ while (wb->remaining != 0) {
+ pthread_cond_wait(&wb->transfer_finish, &wb->writeMutex);
+ }
+ pthread_mutex_unlock(&wb->writeMutex);
+ }
+ return wb;
+}
+
+/**
+ * Free the webhdfsBuffer and destroy its pthread conditions/mutex
+ * @param buffer The webhdfsBuffer to free
+ */
+static void freeWebhdfsBuffer(struct webhdfsBuffer *buffer)
+{
+ int ret = 0;
+ if (buffer) {
+ ret = pthread_cond_destroy(&buffer->newwrite_or_close);
+ if (ret) {
+ fprintf(stderr,
+ "WARN: fail in pthread_cond_destroy for newwrite_or_close "
+ "in freeWebhdfsBuffer, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ errno = ret;
+ }
+ ret = pthread_cond_destroy(&buffer->transfer_finish);
+ if (ret) {
+ fprintf(stderr,
+ "WARN: fail in pthread_cond_destroy for transfer_finish "
+ "in freeWebhdfsBuffer, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ errno = ret;
+ }
+ ret = pthread_mutex_destroy(&buffer->writeMutex);
+ if (ret) {
+ fprintf(stderr,
+ "WARN: fail in pthread_mutex_destroy for writeMutex "
+ "in freeWebhdfsBuffer, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ errno = ret;
+ }
+ free(buffer);
+ buffer = NULL;
+ }
+}
+
+/**
+ * To free the webhdfsFileHandle, which includes a webhdfsBuffer and strings
+ * @param handle The webhdfsFileHandle to free
+ */
+static void freeWebFileHandle(struct webhdfsFileHandle * handle)
+{
+ if (!handle)
+ return;
+ freeWebhdfsBuffer(handle->uploadBuffer);
+ free(handle->datanode);
+ free(handle->absPath);
+ free(handle);
+}
+
+static const char *maybeNull(const char *str)
+{
+ return str ? str : "(NULL)";
+}
+
+/** To print a hdfsBuilder as string */
+static const char *hdfsBuilderToStr(const struct hdfsBuilder *bld,
+ char *buf, size_t bufLen)
+{
+ int strlength = snprintf(buf, bufLen, "nn=%s, port=%d, "
+ "kerbTicketCachePath=%s, userName=%s",
+ maybeNull(bld->nn), bld->port,
+ maybeNull(bld->kerbTicketCachePath), maybeNull(bld->userName));
+ if (strlength < 0 || strlength >= bufLen) {
+ fprintf(stderr, "failed to print a hdfsBuilder as string.\n");
+ return NULL;
+ }
+ return buf;
+}
+
+/**
+ * Free a hdfs_internal handle
+ * @param fs The hdfs_internal handle to free
+ */
+static void freeWebHdfsInternal(struct hdfs_internal *fs)
+{
+ if (fs) {
+ free(fs->nn);
+ free(fs->userName);
+ free(fs->workingDir);
+ }
+}
+
+struct hdfsBuilder *hdfsNewBuilder(void)
+{
+ struct hdfsBuilder *bld = calloc(1, sizeof(struct hdfsBuilder));
+ if (!bld) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ return bld;
+}
+
+void hdfsFreeBuilder(struct hdfsBuilder *bld)
+{
+ free(bld);
+}
+
+void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld)
+{
+ // We don't cache instances in libwebhdfs, so this is not applicable.
+}
+
+void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn)
+{
+ if (bld) {
+ bld->nn = nn;
+ }
+}
+
+void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port)
+{
+ if (bld) {
+ bld->port = port;
+ }
+}
+
+void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName)
+{
+ if (bld) {
+ bld->userName = userName;
+ }
+}
+
+void hdfsBuilderSetKerbTicketCachePath(struct hdfsBuilder *bld,
+ const char *kerbTicketCachePath)
+{
+ if (bld) {
+ bld->kerbTicketCachePath = kerbTicketCachePath;
+ }
+}
+
+hdfsFS hdfsConnectAsUser(const char* nn, tPort port, const char *user)
+{
+ struct hdfsBuilder* bld = hdfsNewBuilder();
+ if (!bld) {
+ return NULL;
+ }
+ hdfsBuilderSetNameNode(bld, nn);
+ hdfsBuilderSetNameNodePort(bld, port);
+ hdfsBuilderSetUserName(bld, user);
+ return hdfsBuilderConnect(bld);
+}
+
+hdfsFS hdfsConnect(const char* nn, tPort port)
+{
+ return hdfsConnectAsUser(nn, port, NULL);
+}
+
+hdfsFS hdfsConnectNewInstance(const char* nn, tPort port)
+{
+ return hdfsConnect(nn, port);
+}
+
+hdfsFS hdfsConnectAsUserNewInstance(const char* host, tPort port,
+ const char *user)
+{
+ struct hdfsBuilder *bld = hdfsNewBuilder();
+ if (!bld)
+ return NULL;
+ hdfsBuilderSetNameNode(bld, host);
+ hdfsBuilderSetNameNodePort(bld, port);
+ hdfsBuilderSetUserName(bld, user);
+ hdfsBuilderSetForceNewInstance(bld);
+ return hdfsBuilderConnect(bld);
+}
+
+/**
+ * To retrieve the default configuration value for NameNode's hostName and port
+ * TODO: This function currently is using JNI,
+ * we need to do this without using JNI (HDFS-3917)
+ *
+ * @param bld The hdfsBuilder handle
+ * @param port Used to get the default value for NameNode's port
+ * @param nn Used to get the default value for NameNode's hostName
+ * @return 0 for success and non-zero value for failure
+ */
+static int retrieveDefaults(const struct hdfsBuilder *bld, tPort *port,
+ char **nn)
+{
+ JNIEnv *env = 0;
+ jobject jHDFSConf = NULL, jAddress = NULL;
+ jstring jHostName = NULL;
+ jvalue jVal;
+ jthrowable jthr = NULL;
+ int ret = 0;
+ char buf[512];
+
+ env = getJNIEnv();
+ if (!env) {
+ return EINTERNAL;
+ }
+
+ jthr = constructNewObjectOfClass(env, &jHDFSConf, HADOOP_HDFS_CONF, "()V");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+
+ jthr = invokeMethod(env, &jVal, STATIC, NULL,
+ HADOOP_NAMENODE, "getHttpAddress",
+ "(Lorg/apache/hadoop/conf/Configuration;)Ljava/net/InetSocketAddress;",
+ jHDFSConf);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jAddress = jVal.l;
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jAddress,
+ JAVA_INETSOCKETADDRESS, "getPort", "()I");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ *port = jVal.i;
+
+ jthr = invokeMethod(env, &jVal, INSTANCE, jAddress,
+ JAVA_INETSOCKETADDRESS,
+ "getHostName", "()Ljava/lang/String;");
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+ jHostName = jVal.l;
+ jthr = newCStr(env, jHostName, nn);
+ if (jthr) {
+ ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
+ "hdfsBuilderConnect(%s)",
+ hdfsBuilderToStr(bld, buf, sizeof(buf)));
+ goto done;
+ }
+
+done:
+ destroyLocalReference(env, jHDFSConf);
+ destroyLocalReference(env, jAddress);
+ destroyLocalReference(env, jHostName);
+ return ret;
+}
+
+hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld)
+{
+ struct hdfs_internal *fs = NULL;
+ int ret = 0;
+
+ if (!bld) {
+ ret = EINVAL;
+ goto done;
+ }
+ if (bld->nn == NULL) {
+ // In the JNI version of libhdfs this returns a LocalFileSystem.
+ ret = ENOTSUP;
+ goto done;
+ }
+
+ fs = calloc(1, sizeof(*fs));
+ if (!fs) {
+ ret = ENOMEM;
+ goto done;
+ }
+ // If the namenode is "default" and/or the port of namenode is 0,
+ // get the default namenode/port
+ if (bld->port == 0 || !strcasecmp("default", bld->nn)) {
+ ret = retrieveDefaults(bld, &fs->port, &fs->nn);
+ if (ret)
+ goto done;
+ } else {
+ fs->port = bld->port;
+ fs->nn = strdup(bld->nn);
+ if (!fs->nn) {
+ ret = ENOMEM;
+ goto done;
+ }
+ }
+ if (bld->userName) {
+ // userName may be NULL
+ fs->userName = strdup(bld->userName);
+ if (!fs->userName) {
+ ret = ENOMEM;
+ goto done;
+ }
+ }
+ // The working directory starts out as root.
+ fs->workingDir = strdup("/");
+ if (!fs->workingDir) {
+ ret = ENOMEM;
+ goto done;
+ }
+ // For debug
+ fprintf(stderr, "namenode: %s:%d\n", bld->nn, bld->port);
+
+done:
+ free(bld);
+ if (ret) {
+ freeWebHdfsInternal(fs);
+ errno = ret;
+ return NULL;
+ }
+ return fs;
+}
+
+int hdfsDisconnect(hdfsFS fs)
+{
+ if (fs == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+ freeWebHdfsInternal(fs);
+ return 0;
+}
+
+/**
+ * Based on the working directory stored in hdfsFS,
+ * generate the absolute path for the given path
+ *
+ * @param fs The hdfsFS handle which stores the current working directory
+ * @param path The given path which may not be an absolute path
+ * @param absPath To hold generated absolute path for the given path
+ * @return 0 on success, non-zero value indicating error
+ */
+static int getAbsolutePath(hdfsFS fs, const char *path, char **absPath)
+{
+ char *tempPath = NULL;
+ size_t absPathLen;
+ int strlength;
+
+ if (path[0] == '/') {
+ // Path is already absolute.
+ tempPath = strdup(path);
+ if (!tempPath) {
+ return ENOMEM;
+ }
+ *absPath = tempPath;
+ return 0;
+ }
+ // Prepend the workingDir to the path.
+ absPathLen = strlen(fs->workingDir) + strlen(path) + 1;
+ tempPath = malloc(absPathLen);
+ if (!tempPath) {
+ return ENOMEM;
+ }
+ strlength = snprintf(tempPath, absPathLen, "%s%s", fs->workingDir, path);
+ if (strlength < 0 || strlength >= absPathLen) {
+ free(tempPath);
+ return EIO;
+ }
+ *absPath = tempPath;
+ return 0;
+}
+
+int hdfsCreateDirectory(hdfsFS fs, const char* path)
+{
+ char *url = NULL, *absPath = NULL;
+ struct Response *resp = NULL;
+ int ret = 0;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ ret = getAbsolutePath(fs, path, &absPath);
+ if (ret) {
+ goto done;
+ }
+ ret = createUrlForMKDIR(fs->nn, fs->port, absPath, fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchMKDIR(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseMKDIR(resp->body->content);
+done:
+ freeResponse(resp);
+ free(url);
+ free(absPath);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsChmod(hdfsFS fs, const char* path, short mode)
+{
+ char *absPath = NULL, *url = NULL;
+ struct Response *resp = NULL;
+ int ret = 0;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ ret = getAbsolutePath(fs, path, &absPath);
+ if (ret) {
+ goto done;
+ }
+ ret = createUrlForCHMOD(fs->nn, fs->port, absPath, (int) mode,
+ fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchCHMOD(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseCHMOD(resp->header->content, resp->body->content);
+done:
+ freeResponse(resp);
+ free(absPath);
+ free(url);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsChown(hdfsFS fs, const char* path, const char *owner, const char *group)
+{
+ int ret = 0;
+ char *absPath = NULL, *url = NULL;
+ struct Response *resp = NULL;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+
+ ret = getAbsolutePath(fs, path, &absPath);
+ if (ret) {
+ goto done;
+ }
+ ret = createUrlForCHOWN(fs->nn, fs->port, absPath,
+ owner, group, fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchCHOWN(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseCHOWN(resp->header->content, resp->body->content);
+done:
+ freeResponse(resp);
+ free(absPath);
+ free(url);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath)
+{
+ char *oldAbsPath = NULL, *newAbsPath = NULL, *url = NULL;
+ int ret = 0;
+ struct Response *resp = NULL;
+
+ if (fs == NULL || oldPath == NULL || newPath == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ ret = getAbsolutePath(fs, oldPath, &oldAbsPath);
+ if (ret) {
+ goto done;
+ }
+ ret = getAbsolutePath(fs, newPath, &newAbsPath);
+ if (ret) {
+ goto done;
+ }
+ ret = createUrlForRENAME(fs->nn, fs->port, oldAbsPath,
+ newAbsPath, fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchRENAME(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseRENAME(resp->body->content);
+done:
+ freeResponse(resp);
+ free(oldAbsPath);
+ free(newAbsPath);
+ free(url);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+/**
+ * Get the file status for a given path.
+ *
+ * @param fs hdfsFS handle containing
+ * NameNode hostName/port information
+ * @param path Path for file
+ * @param printError Whether or not to print out error information
+ * (mainly remote FileNotFoundException)
+ * @return File information for the given path
+ */
+static hdfsFileInfo *hdfsGetPathInfoImpl(hdfsFS fs, const char* path,
+ int printError)
+{
+ char *absPath = NULL;
+ char *url=NULL;
+ struct Response *resp = NULL;
+ int ret = 0;
+ hdfsFileInfo *fileInfo = NULL;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ ret = getAbsolutePath(fs, path, &absPath);
+ if (ret) {
+ goto done;
+ }
+ fileInfo = (hdfsFileInfo *) calloc(1, sizeof(hdfsFileInfo));
+ if (!fileInfo) {
+ ret = ENOMEM;
+ goto done;
+ }
+ fileInfo->mKind = kObjectKindFile;
+
+ ret = createUrlForGetFileStatus(fs->nn, fs->port, absPath,
+ fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchGFS(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseGFS(resp->body->content, fileInfo, printError);
+
+done:
+ freeResponse(resp);
+ free(absPath);
+ free(url);
+ if (ret == 0) {
+ return fileInfo;
+ } else {
+ free(fileInfo);
+ errno = ret;
+ return NULL;
+ }
+}
+
+hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path)
+{
+ return hdfsGetPathInfoImpl(fs, path, 1);
+}
+
+hdfsFileInfo *hdfsListDirectory(hdfsFS fs, const char* path, int *numEntries)
+{
+ char *url = NULL, *absPath = NULL;
+ struct Response *resp = NULL;
+ int ret = 0;
+ hdfsFileInfo *fileInfo = NULL;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ ret = getAbsolutePath(fs, path, &absPath);
+ if (ret) {
+ goto done;
+ }
+ fileInfo = calloc(1, sizeof(*fileInfo));
+ if (!fileInfo) {
+ ret = ENOMEM;
+ goto done;
+ }
+
+ ret = createUrlForLS(fs->nn, fs->port, absPath, fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchLS(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseLS(resp->body->content, &fileInfo, numEntries);
+
+done:
+ freeResponse(resp);
+ free(absPath);
+ free(url);
+ if (ret == 0) {
+ return fileInfo;
+ } else {
+ errno = ret;
+ return NULL;
+ }
+}
+
+int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication)
+{
+ char *url = NULL, *absPath = NULL;
+ struct Response *resp = NULL;
+ int ret = 0;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ ret = getAbsolutePath(fs, path, &absPath);
+ if (ret) {
+ goto done;
+ }
+
+ ret = createUrlForSETREPLICATION(fs->nn, fs->port, absPath,
+ replication, fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchSETREPLICATION(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseSETREPLICATION(resp->body->content);
+done:
+ freeResponse(resp);
+ free(absPath);
+ free(url);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries)
+{
+ int i;
+ for (i = 0; i < numEntries; ++i) {
+ free(hdfsFileInfo[i].mName);
+ free(hdfsFileInfo[i].mOwner);
+ free(hdfsFileInfo[i].mGroup);
+ }
+ free(hdfsFileInfo);
+}
+
+int hdfsDelete(hdfsFS fs, const char* path, int recursive)
+{
+ char *url = NULL, *absPath = NULL;
+ struct Response *resp = NULL;
+ int ret = 0;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ ret = getAbsolutePath(fs, path, &absPath);
+ if (ret) {
+ goto done;
+ }
+
+ ret = createUrlForDELETE(fs->nn, fs->port, absPath,
+ recursive, fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchDELETE(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseDELETE(resp->body->content);
+done:
+ freeResponse(resp);
+ free(absPath);
+ free(url);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime)
+{
+ char *url = NULL, *absPath = NULL;
+ struct Response *resp = NULL;
+ int ret = 0;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ ret = getAbsolutePath(fs, path, &absPath);
+ if (ret) {
+ goto done;
+ }
+
+ ret = createUrlForUTIMES(fs->nn, fs->port, absPath, mtime, atime,
+ fs->userName, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchUTIMES(url, &resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseUTIMES(resp->header->content, resp->body->content);
+done:
+ freeResponse(resp);
+ free(absPath);
+ free(url);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsExists(hdfsFS fs, const char *path)
+{
+ hdfsFileInfo *fileInfo = hdfsGetPathInfoImpl(fs, path, 0);
+ if (!fileInfo) {
+ // (errno will have been set by hdfsGetPathInfo)
+ return -1;
+ }
+ hdfsFreeFileInfo(fileInfo, 1);
+ return 0;
+}
+
+/**
+ * The information hold by the thread which writes data to hdfs through http
+ */
+typedef struct {
+ char *url; /* the url of the target datanode for writing*/
+ struct webhdfsBuffer *uploadBuffer; /* buffer storing data to write */
+ int flags; /* flag indicating writing mode: create or append */
+ struct Response *resp; /* response from the target datanode */
+} threadData;
+
+/**
+ * Free the threadData struct instance,
+ * including the response and url contained in it
+ * @param data The threadData instance to free
+ */
+static void freeThreadData(threadData *data)
+{
+ if (data) {
+ if (data->url) {
+ free(data->url);
+ }
+ if (data->resp) {
+ freeResponse(data->resp);
+ }
+ // The uploadBuffer would be freed by freeWebFileHandle()
+ free(data);
+ data = NULL;
+ }
+}
+
+/**
+ * The action of the thread that writes data to
+ * the target datanode for hdfsWrite.
+ * The writing can be either create or append, which is specified by flag
+ */
+static void *writeThreadOperation(void *v)
+{
+ int ret = 0;
+ threadData *data = v;
+ if (data->flags & O_APPEND) {
+ ret = launchDnAPPEND(data->url, data->uploadBuffer, &(data->resp));
+ } else {
+ ret = launchDnWRITE(data->url, data->uploadBuffer, &(data->resp));
+ }
+ if (ret) {
+ fprintf(stderr, "Failed to write to datanode %s, <%d>: %s.\n",
+ data->url, ret, hdfs_strerror(ret));
+ }
+ return data;
+}
+
+/**
+ * Free the memory associated with a webHDFS file handle.
+ *
+ * No other resources will be freed.
+ *
+ * @param file The webhdfs file handle
+ */
+static void freeFileInternal(hdfsFile file)
+{
+ if (!file)
+ return;
+ freeWebFileHandle(file->file);
+ free(file);
+}
+
+/**
+ * Helper function for opening a file for OUTPUT.
+ *
+ * As part of the open process for OUTPUT files, we have to connect to the
+ * NameNode and get the URL of the corresponding DataNode.
+ * We also create a background thread here for doing I/O.
+ *
+ * @param webhandle The webhandle being opened
+ * @return 0 on success; error code otherwise
+ */
+static int hdfsOpenOutputFileImpl(hdfsFS fs, hdfsFile file)
+{
+ struct webhdfsFileHandle *webhandle = file->file;
+ struct Response *resp = NULL;
+ int append, ret = 0;
+ char *nnUrl = NULL, *dnUrl = NULL;
+ threadData *data = NULL;
+
+ ret = initWebHdfsBuffer(&webhandle->uploadBuffer);
+ if (ret) {
+ goto done;
+ }
+ append = file->flags & O_APPEND;
+ if (!append) {
+ // If we're not appending, send a create request to the NN
+ ret = createUrlForNnWRITE(fs->nn, fs->port, webhandle->absPath,
+ fs->userName, webhandle->replication,
+ webhandle->blockSize, &nnUrl);
+ } else {
+ ret = createUrlForNnAPPEND(fs->nn, fs->port, webhandle->absPath,
+ fs->userName, &nnUrl);
+ }
+ if (ret) {
+ fprintf(stderr, "Failed to create the url connecting to namenode "
+ "for file creation/appending, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ goto done;
+ }
+ if (!append) {
+ ret = launchNnWRITE(nnUrl, &resp);
+ } else {
+ ret = launchNnAPPEND(nnUrl, &resp);
+ }
+ if (ret) {
+ fprintf(stderr, "fail to get the response from namenode for "
+ "file creation/appending, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ goto done;
+ }
+ if (!append) {
+ ret = parseNnWRITE(resp->header->content, resp->body->content);
+ } else {
+ ret = parseNnAPPEND(resp->header->content, resp->body->content);
+ }
+ if (ret) {
+ fprintf(stderr, "fail to parse the response from namenode for "
+ "file creation/appending, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ goto done;
+ }
+ ret = parseDnLoc(resp->header->content, &dnUrl);
+ if (ret) {
+ fprintf(stderr, "fail to get the datanode url from namenode "
+ "for file creation/appending, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ goto done;
+ }
+ //store the datanode url in the file handle
+ webhandle->datanode = strdup(dnUrl);
+ if (!webhandle->datanode) {
+ ret = ENOMEM;
+ goto done;
+ }
+ //create a new thread for performing the http transferring
+ data = calloc(1, sizeof(*data));
+ if (!data) {
+ ret = ENOMEM;
+ goto done;
+ }
+ data->url = strdup(dnUrl);
+ if (!data->url) {
+ ret = ENOMEM;
+ goto done;
+ }
+ data->flags = file->flags;
+ data->uploadBuffer = webhandle->uploadBuffer;
+ ret = pthread_create(&webhandle->connThread, NULL,
+ writeThreadOperation, data);
+ if (ret) {
+ fprintf(stderr, "ERROR: failed to create the writing thread "
+ "in hdfsOpenOutputFileImpl, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ goto done;
+ }
+ webhandle->uploadBuffer->openFlag = 1;
+
+done:
+ freeResponse(resp);
+ free(nnUrl);
+ free(dnUrl);
+ if (ret) {
+ errno = ret;
+ if (data) {
+ free(data->url);
+ free(data);
+ }
+ }
+ return ret;
+}
+
+hdfsFile hdfsOpenFile(hdfsFS fs, const char* path, int flags,
+ int bufferSize, short replication, tSize blockSize)
+{
+ int ret = 0;
+ int accmode = flags & O_ACCMODE;
+ struct webhdfsFileHandle *webhandle = NULL;
+ hdfsFile file = NULL;
+
+ if (fs == NULL || path == NULL) {
+ ret = EINVAL;
+ goto done;
+ }
+ if (accmode == O_RDWR) {
+ // TODO: the original libhdfs has very hackish support for this; should
+ // we do the same? It would actually be a lot easier in libwebhdfs
+ // since the protocol isn't connection-oriented.
+ fprintf(stderr, "ERROR: cannot open an hdfs file in O_RDWR mode\n");
+ ret = ENOTSUP;
+ goto done;
+ }
+ if ((flags & O_CREAT) && (flags & O_EXCL)) {
+ fprintf(stderr,
+ "WARN: hdfs does not truly support O_CREATE && O_EXCL\n");
+ }
+ file = calloc(1, sizeof(struct hdfsFile_internal));
+ if (!file) {
+ ret = ENOMEM;
+ goto done;
+ }
+ file->flags = flags;
+ file->type = accmode == O_RDONLY ? INPUT : OUTPUT;
+ file->offset = 0;
+ webhandle = calloc(1, sizeof(struct webhdfsFileHandle));
+ if (!webhandle) {
+ ret = ENOMEM;
+ goto done;
+ }
+ webhandle->bufferSize = bufferSize;
+ webhandle->replication = replication;
+ webhandle->blockSize = blockSize;
+ ret = getAbsolutePath(fs, path, &webhandle->absPath);
+ if (ret) {
+ goto done;
+ }
+ file->file = webhandle;
+ // If open for write/append,
+ // open and keep the connection with the target datanode for writing
+ if (file->type == OUTPUT) {
+ ret = hdfsOpenOutputFileImpl(fs, file);
+ if (ret) {
+ goto done;
+ }
+ }
+
+done:
+ if (ret) {
+ if (file) {
+ freeFileInternal(file); // Also frees webhandle
+ } else {
+ freeWebFileHandle(webhandle);
+ }
+ errno = ret;
+ return NULL;
+ }
+ return file;
+}
+
+int hdfsTruncateFile(hdfsFS fs, const char* path, tOffset newlength)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
+tSize hdfsWrite(hdfsFS fs, hdfsFile file, const void* buffer, tSize length)
+{
+ if (length == 0) {
+ return 0;
+ }
+ if (fs == NULL || file == NULL || file->type != OUTPUT || length < 0) {
+ errno = EBADF;
+ return -1;
+ }
+
+ struct webhdfsFileHandle *wfile = file->file;
+ if (wfile->uploadBuffer && wfile->uploadBuffer->openFlag) {
+ resetWebhdfsBuffer(wfile->uploadBuffer, buffer, length);
+ return length;
+ } else {
+ fprintf(stderr,
+ "Error: have not opened the file %s for writing yet.\n",
+ wfile->absPath);
+ errno = EBADF;
+ return -1;
+ }
+}
+
+int hdfsCloseFile(hdfsFS fs, hdfsFile file)
+{
+ void *respv = NULL;
+ threadData *tdata = NULL;
+ int ret = 0;
+ struct webhdfsFileHandle *wfile = NULL;
+
+ if (file->type == OUTPUT) {
+ wfile = file->file;
+ pthread_mutex_lock(&(wfile->uploadBuffer->writeMutex));
+ wfile->uploadBuffer->closeFlag = 1;
+ pthread_cond_signal(&wfile->uploadBuffer->newwrite_or_close);
+ pthread_mutex_unlock(&(wfile->uploadBuffer->writeMutex));
+
+ // Waiting for the writing thread to terminate
+ ret = pthread_join(wfile->connThread, &respv);
+ if (ret) {
+ fprintf(stderr, "Error when pthread_join in hdfsClose, <%d>: %s.\n",
+ ret, hdfs_strerror(ret));
+ }
+ // Parse the response
+ tdata = respv;
+ if (!tdata || !(tdata->resp)) {
+ fprintf(stderr,
+ "ERROR: response from the writing thread is NULL.\n");
+ ret = EIO;
+ }
+ if (file->flags & O_APPEND) {
+ ret = parseDnAPPEND(tdata->resp->header->content,
+ tdata->resp->body->content);
+ } else {
+ ret = parseDnWRITE(tdata->resp->header->content,
+ tdata->resp->body->content);
+ }
+ // Free the threaddata
+ freeThreadData(tdata);
+ }
+ freeFileInternal(file);
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+int hdfsFileIsOpenForRead(hdfsFile file)
+{
+ return (file->type == INPUT);
+}
+
+int hdfsFileGetReadStatistics(hdfsFile file,
+ struct hdfsReadStatistics **stats)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
+int64_t hdfsReadStatisticsGetRemoteBytesRead(
+ const struct hdfsReadStatistics *stats)
+{
+ return stats->totalBytesRead - stats->totalLocalBytesRead;
+}
+
+void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats)
+{
+ free(stats);
+}
+
+int hdfsFileIsOpenForWrite(hdfsFile file)
+{
+ return (file->type == OUTPUT);
+}
+
+static int hdfsReadImpl(hdfsFS fs, hdfsFile file, void* buffer, tSize off,
+ tSize length, tSize *numRead)
+{
+ int ret = 0;
+ char *url = NULL;
+ struct Response *resp = NULL;
+
+ if (fs == NULL || file == NULL || file->type != INPUT || buffer == NULL ||
+ length < 0) {
+ ret = EINVAL;
+ goto done;
+ }
+ if (length == 0) {
+ // Special case: the user supplied a buffer of zero length, so there is
+ // nothing to do.
+ *numRead = 0;
+ goto done;
+ }
+ resp = calloc(1, sizeof(*resp)); // resp is actually a pointer type
+ if (!resp) {
+ ret = ENOMEM;
+ goto done;
+ }
+ ret = initResponseBuffer(&(resp->header));
+ if (ret) {
+ goto done;
+ }
+ ret = initResponseBuffer(&(resp->body));
+ if (ret) {
+ goto done;
+ }
+ memset(buffer, 0, length);
+ resp->body->content = buffer;
+ resp->body->remaining = length;
+
+ ret = createUrlForOPEN(fs->nn, fs->port, file->file->absPath,
+ fs->userName, off, length, &url);
+ if (ret) {
+ goto done;
+ }
+ ret = launchOPEN(url, resp);
+ if (ret) {
+ goto done;
+ }
+ ret = parseOPEN(resp->header->content, resp->body->content);
+ if (ret == -1) {
+ // Special case: if parseOPEN returns -1, we asked for a byte range
+ // with outside what the file contains. In this case, hdfsRead and
+ // hdfsPread return 0, meaning end-of-file.
+ *numRead = 0;
+ } else if (ret == 0) {
+ *numRead = (tSize) resp->body->offset;
+ }
+done:
+ if (resp) {
+ freeResponseBuffer(resp->header);
+ free(resp->body);
+ }
+ free(resp);
+ free(url);
+ return ret;
+}
+
+tSize hdfsRead(hdfsFS fs, hdfsFile file, void* buffer, tSize length)
+{
+ int ret = 0;
+ tSize numRead = 0;
+
+ ret = hdfsReadImpl(fs, file, buffer, (tSize) file->offset,
+ length, &numRead);
+ if (ret > 0) { // ret == -1 means end of file
+ errno = ret;
+ return -1;
+ }
+ file->offset += numRead;
+ return numRead;
+}
+
+int hdfsAvailable(hdfsFS fs, hdfsFile file)
+{
+ /* We actually always block when reading from webhdfs, currently. So the
+ * number of bytes that can be read without blocking is currently 0.
+ */
+ return 0;
+}
+
+int hdfsSeek(hdfsFS fs, hdfsFile file, tOffset desiredPos)
+{
+ struct webhdfsFileHandle *wf;
+ hdfsFileInfo *fileInfo = NULL;
+ int ret = 0;
+
+ if (!fs || !file || (file->type == OUTPUT) || (desiredPos < 0)) {
+ ret = EINVAL;
+ goto done;
+ }
+ wf = file->file;
+ if (!wf) {
+ ret = EINVAL;
+ goto done;
+ }
+ fileInfo = hdfsGetPathInfo(fs, wf->absPath);
+ if (!fileInfo) {
+ ret = errno;
+ goto done;
+ }
+ if (desiredPos > fileInfo->mSize) {
+ fprintf(stderr,
+ "hdfsSeek for %s failed since the desired position %" PRId64
+ " is beyond the size of the file %" PRId64 "\n",
+ wf->absPath, desiredPos, fileInfo->mSize);
+ ret = ENOTSUP;
+ goto done;
+ }
+ file->offset = desiredPos;
+
+done:
+ if (fileInfo) {
+ hdfsFreeFileInfo(fileInfo, 1);
+ }
+ if (ret) {
+ errno = ret;
+ return -1;
+ }
+ return 0;
+}
+
+tSize hdfsPread(hdfsFS fs, hdfsFile file, tOffset position,
+ void* buffer, tSize length)
+{
+ int ret;
+ tSize numRead = 0;
+
+ if (position < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ ret = hdfsReadImpl(fs, file, buffer, (tSize) position, length, &numRead);
+ if (ret > 0) {
+ errno = ret;
+ return -1;
+ }
+ return numRead;
+}
+
+tOffset hdfsTell(hdfsFS fs, hdfsFile file)
+{
+ if (!file) {
+ errno = EINVAL;
+ return -1;
+ }
+ return file->offset;
+}
+
+char* hdfsGetWorkingDirectory(hdfsFS fs, char *buffer, size_t bufferSize)
+{
+ int strlength;
+ if (fs == NULL || buffer == NULL || bufferSize <= 0) {
+ errno = EINVAL;
+ return NULL;
+ }
+ strlength = snprintf(buffer, bufferSize, "%s", fs->workingDir);
+ if (strlength >= bufferSize) {
+ errno = ENAMETOOLONG;
+ return NULL;
+ } else if (strlength < 0) {
+ errno = EIO;
+ return NULL;
+ }
+ return buffer;
+}
+
+/** Replace "//" with "/" in path */
+static void normalizePath(char *path)
+{
+ int i = 0, j = 0, sawslash = 0;
+
+ for (i = j = sawslash = 0; path[i] != '\0'; i++) {
+ if (path[i] != '/') {
+ sawslash = 0;
+ path[j++] = path[i];
+ } else if (path[i] == '/' && !sawslash) {
+ sawslash = 1;
+ path[j++] = '/';
+ }
+ }
+ path[j] = '\0';
+}
+
+int hdfsSetWorkingDirectory(hdfsFS fs, const char* path)
+{
+ char *newWorkingDir = NULL;
+ size_t strlenPath = 0, newWorkingDirLen = 0;
+ int strlength;
+
+ if (fs == NULL || path == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+ strlenPath = strlen(path);
+ if (strlenPath < 1) {
+ errno = EINVAL;
+ return -1;
+ }
+ // the max string length of the new working dir is
+ // (length of old working dir) + (length of given path) + strlen("/") + 1
+ newWorkingDirLen = strlen(fs->workingDir) + strlenPath + 2;
+ newWorkingDir = malloc(newWorkingDirLen);
+ if (!newWorkingDir) {
+ errno = ENOMEM;
+ return -1;
+ }
+ strlength = snprintf(newWorkingDir, newWorkingDirLen, "%s%s%s",
+ (path[0] == '/') ? "" : fs->workingDir,
+ path, (path[strlenPath - 1] == '/') ? "" : "/");
+ if (strlength < 0 || strlength >= newWorkingDirLen) {
+ free(newWorkingDir);
+ errno = EIO;
+ return -1;
+ }
+
+ if (strstr(path, "//")) {
+ // normalize the path by replacing "//" with "/"
+ normalizePath(newWorkingDir);
+ }
+
+ free(fs->workingDir);
+ fs->workingDir = newWorkingDir;
+ return 0;
+}
+
+void hdfsFreeHosts(char ***blockHosts)
+{
+ int i, j;
+ for (i=0; blockHosts[i]; i++) {
+ for (j=0; blockHosts[i][j]; j++) {
+ free(blockHosts[i][j]);
+ }
+ free(blockHosts[i]);
+ }
+ free(blockHosts);
+}
+
+tOffset hdfsGetDefaultBlockSize(hdfsFS fs)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
+int hdfsFileUsesDirectRead(hdfsFile file)
+{
+ return 0; // webhdfs never performs direct reads.
+}
+
+void hdfsFileDisableDirectRead(hdfsFile file)
+{
+ // webhdfs never performs direct reads
+}
+
+int hdfsHFlush(hdfsFS fs, hdfsFile file)
+{
+ if (file->type != OUTPUT) {
+ errno = EINVAL;
+ return -1;
+ }
+ // TODO: block until our write buffer is flushed (HDFS-3952)
+ return 0;
+}
+
+int hdfsFlush(hdfsFS fs, hdfsFile file)
+{
+ if (file->type != OUTPUT) {
+ errno = EINVAL;
+ return -1;
+ }
+ // TODO: block until our write buffer is flushed (HDFS-3952)
+ return 0;
+}
+
+char*** hdfsGetHosts(hdfsFS fs, const char* path,
+ tOffset start, tOffset length)
+{
+ errno = ENOTSUP;
+ return NULL;
+}
+
+tOffset hdfsGetCapacity(hdfsFS fs)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
+tOffset hdfsGetUsed(hdfsFS fs)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
+int hdfsCopy(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
+int hdfsMove(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
[19/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/common/htable.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/common/htable.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/common/htable.c
new file mode 100644
index 0000000..50c89ea
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/common/htable.c
@@ -0,0 +1,287 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "common/htable.h"
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+struct htable_pair {
+ void *key;
+ void *val;
+};
+
+/**
+ * A hash table which uses linear probing.
+ */
+struct htable {
+ uint32_t capacity;
+ uint32_t used;
+ htable_hash_fn_t hash_fun;
+ htable_eq_fn_t eq_fun;
+ struct htable_pair *elem;
+};
+
+/**
+ * An internal function for inserting a value into the hash table.
+ *
+ * Note: this function assumes that you have made enough space in the table.
+ *
+ * @param nelem The new element to insert.
+ * @param capacity The capacity of the hash table.
+ * @param hash_fun The hash function to use.
+ * @param key The key to insert.
+ * @param val The value to insert.
+ */
+static void htable_insert_internal(struct htable_pair *nelem,
+ uint32_t capacity, htable_hash_fn_t hash_fun, void *key,
+ void *val)
+{
+ uint32_t i;
+
+ i = hash_fun(key, capacity);
+ while (1) {
+ if (!nelem[i].key) {
+ nelem[i].key = key;
+ nelem[i].val = val;
+ return;
+ }
+ i++;
+ if (i == capacity) {
+ i = 0;
+ }
+ }
+}
+
+static int htable_realloc(struct htable *htable, uint32_t new_capacity)
+{
+ struct htable_pair *nelem;
+ uint32_t i, old_capacity = htable->capacity;
+ htable_hash_fn_t hash_fun = htable->hash_fun;
+
+ nelem = calloc(new_capacity, sizeof(struct htable_pair));
+ if (!nelem) {
+ return ENOMEM;
+ }
+ for (i = 0; i < old_capacity; i++) {
+ struct htable_pair *pair = htable->elem + i;
+ if (pair->key) {
+ htable_insert_internal(nelem, new_capacity, hash_fun,
+ pair->key, pair->val);
+ }
+ }
+ free(htable->elem);
+ htable->elem = nelem;
+ htable->capacity = new_capacity;
+ return 0;
+}
+
+static uint32_t round_up_to_power_of_2(uint32_t i)
+{
+ if (i == 0) {
+ return 1;
+ }
+ i--;
+ i |= i >> 1;
+ i |= i >> 2;
+ i |= i >> 4;
+ i |= i >> 8;
+ i |= i >> 16;
+ i++;
+ return i;
+}
+
+struct htable *htable_alloc(uint32_t size,
+ htable_hash_fn_t hash_fun, htable_eq_fn_t eq_fun)
+{
+ struct htable *htable;
+
+ htable = calloc(1, sizeof(*htable));
+ if (!htable) {
+ return NULL;
+ }
+ size = round_up_to_power_of_2(size);
+ if (size < HTABLE_MIN_SIZE) {
+ size = HTABLE_MIN_SIZE;
+ }
+ htable->hash_fun = hash_fun;
+ htable->eq_fun = eq_fun;
+ htable->used = 0;
+ if (htable_realloc(htable, size)) {
+ free(htable);
+ return NULL;
+ }
+ return htable;
+}
+
+void htable_visit(struct htable *htable, visitor_fn_t fun, void *ctx)
+{
+ uint32_t i;
+
+ for (i = 0; i != htable->capacity; ++i) {
+ struct htable_pair *elem = htable->elem + i;
+ if (elem->key) {
+ fun(ctx, elem->key, elem->val);
+ }
+ }
+}
+
+void htable_free(struct htable *htable)
+{
+ if (htable) {
+ free(htable->elem);
+ free(htable);
+ }
+}
+
+int htable_put(struct htable *htable, void *key, void *val)
+{
+ int ret;
+ uint32_t nused;
+
+ // NULL is not a valid key value.
+ // This helps us implement htable_get_internal efficiently, since we know
+ // that we can stop when we encounter the first NULL key.
+ if (!key) {
+ return EINVAL;
+ }
+ // NULL is not a valid value. Otherwise the results of htable_get would
+ // be confusing (does a NULL return mean entry not found, or that the
+ // entry was found and was NULL?)
+ if (!val) {
+ return EINVAL;
+ }
+ // Re-hash if we have used more than half of the hash table
+ nused = htable->used + 1;
+ if (nused >= (htable->capacity / 2)) {
+ ret = htable_realloc(htable, htable->capacity * 2);
+ if (ret)
+ return ret;
+ }
+ htable_insert_internal(htable->elem, htable->capacity,
+ htable->hash_fun, key, val);
+ htable->used++;
+ return 0;
+}
+
+static int htable_get_internal(const struct htable *htable,
+ const void *key, uint32_t *out)
+{
+ uint32_t start_idx, idx;
+
+ start_idx = htable->hash_fun(key, htable->capacity);
+ idx = start_idx;
+ while (1) {
+ struct htable_pair *pair = htable->elem + idx;
+ if (!pair->key) {
+ // We always maintain the invariant that the entries corresponding
+ // to a given key are stored in a contiguous block, not separated
+ // by any NULLs. So if we encounter a NULL, our search is over.
+ return ENOENT;
+ } else if (htable->eq_fun(pair->key, key)) {
+ *out = idx;
+ return 0;
+ }
+ idx++;
+ if (idx == htable->capacity) {
+ idx = 0;
+ }
+ if (idx == start_idx) {
+ return ENOENT;
+ }
+ }
+}
+
+void *htable_get(const struct htable *htable, const void *key)
+{
+ uint32_t idx;
+
+ if (htable_get_internal(htable, key, &idx)) {
+ return NULL;
+ }
+ return htable->elem[idx].val;
+}
+
+void htable_pop(struct htable *htable, const void *key,
+ void **found_key, void **found_val)
+{
+ uint32_t hole, i;
+ const void *nkey;
+
+ if (htable_get_internal(htable, key, &hole)) {
+ *found_key = NULL;
+ *found_val = NULL;
+ return;
+ }
+ i = hole;
+ htable->used--;
+ // We need to maintain the compactness invariant used in
+ // htable_get_internal. This invariant specifies that the entries for any
+ // given key are never separated by NULLs (although they may be separated
+ // by entries for other keys.)
+ while (1) {
+ i++;
+ if (i == htable->capacity) {
+ i = 0;
+ }
+ nkey = htable->elem[i].key;
+ if (!nkey) {
+ *found_key = htable->elem[hole].key;
+ *found_val = htable->elem[hole].val;
+ htable->elem[hole].key = NULL;
+ htable->elem[hole].val = NULL;
+ return;
+ } else if (htable->eq_fun(key, nkey)) {
+ htable->elem[hole].key = htable->elem[i].key;
+ htable->elem[hole].val = htable->elem[i].val;
+ hole = i;
+ }
+ }
+}
+
+uint32_t htable_used(const struct htable *htable)
+{
+ return htable->used;
+}
+
+uint32_t htable_capacity(const struct htable *htable)
+{
+ return htable->capacity;
+}
+
+uint32_t ht_hash_string(const void *str, uint32_t max)
+{
+ const char *s = str;
+ uint32_t hash = 0;
+
+ while (*s) {
+ hash = (hash * 31) + *s;
+ s++;
+ }
+ return hash % max;
+}
+
+int ht_compare_string(const void *a, const void *b)
+{
+ return strcmp(a, b) == 0;
+}
+
+// vim: ts=4:sw=4:tw=79:et
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/common/htable.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/common/htable.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/common/htable.h
new file mode 100644
index 0000000..33f1229
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/common/htable.h
@@ -0,0 +1,161 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef HADOOP_CORE_COMMON_HASH_TABLE
+#define HADOOP_CORE_COMMON_HASH_TABLE
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdint.h>
+
+#define HTABLE_MIN_SIZE 4
+
+struct htable;
+
+/**
+ * An HTable hash function.
+ *
+ * @param key The key.
+ * @param capacity The total capacity.
+ *
+ * @return The hash slot. Must be less than the capacity.
+ */
+typedef uint32_t (*htable_hash_fn_t)(const void *key, uint32_t capacity);
+
+/**
+ * An HTable equality function. Compares two keys.
+ *
+ * @param a First key.
+ * @param b Second key.
+ *
+ * @return nonzero if the keys are equal.
+ */
+typedef int (*htable_eq_fn_t)(const void *a, const void *b);
+
+/**
+ * Allocate a new hash table.
+ *
+ * @param capacity The minimum suggested starting capacity.
+ * @param hash_fun The hash function to use in this hash table.
+ * @param eq_fun The equals function to use in this hash table.
+ *
+ * @return The new hash table on success; NULL on OOM.
+ */
+struct htable *htable_alloc(uint32_t capacity, htable_hash_fn_t hash_fun,
+ htable_eq_fn_t eq_fun);
+
+typedef void (*visitor_fn_t)(void *ctx, void *key, void *val);
+
+/**
+ * Visit all of the entries in the hash table.
+ *
+ * @param htable The hash table.
+ * @param fun The callback function to invoke on each key and value.
+ * @param ctx Context pointer to pass to the callback.
+ */
+void htable_visit(struct htable *htable, visitor_fn_t fun, void *ctx);
+
+/**
+ * Free the hash table.
+ *
+ * It is up the calling code to ensure that the keys and values inside the
+ * table are de-allocated, if that is necessary.
+ *
+ * @param htable The hash table.
+ */
+void htable_free(struct htable *htable);
+
+/**
+ * Add an entry to the hash table.
+ *
+ * @param htable The hash table.
+ * @param key The key to add. This cannot be NULL.
+ * @param fun The value to add. This cannot be NULL.
+ *
+ * @return 0 on success;
+ * EEXIST if the value already exists in the table;
+ * ENOMEM if there is not enough memory to add the element.
+ * EFBIG if the hash table has too many entries to fit in 32
+ * bits.
+ */
+int htable_put(struct htable *htable, void *key, void *val);
+
+/**
+ * Get an entry from the hash table.
+ *
+ * @param htable The hash table.
+ * @param key The key to find.
+ *
+ * @return NULL if there is no such entry; the entry otherwise.
+ */
+void *htable_get(const struct htable *htable, const void *key);
+
+/**
+ * Get an entry from the hash table and remove it.
+ *
+ * @param htable The hash table.
+ * @param key The key for the entry find and remove.
+ * @param found_key (out param) NULL if the entry was not found; the found key
+ * otherwise.
+ * @param found_val (out param) NULL if the entry was not found; the found
+ * value otherwise.
+ */
+void htable_pop(struct htable *htable, const void *key,
+ void **found_key, void **found_val);
+
+/**
+ * Get the number of entries used in the hash table.
+ *
+ * @param htable The hash table.
+ *
+ * @return The number of entries used in the hash table.
+ */
+uint32_t htable_used(const struct htable *htable);
+
+/**
+ * Get the capacity of the hash table.
+ *
+ * @param htable The hash table.
+ *
+ * @return The capacity of the hash table.
+ */
+uint32_t htable_capacity(const struct htable *htable);
+
+/**
+ * Hash a string.
+ *
+ * @param str The string.
+ * @param max Maximum hash value
+ *
+ * @return A number less than max.
+ */
+uint32_t ht_hash_string(const void *str, uint32_t max);
+
+/**
+ * Compare two strings.
+ *
+ * @param a The first string.
+ * @param b The second string.
+ *
+ * @return 1 if the strings are identical; 0 otherwise.
+ */
+int ht_compare_string(const void *a, const void *b);
+
+#endif
+
+// vim: ts=4:sw=4:tw=79:et
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/exception.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/exception.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/exception.c
new file mode 100644
index 0000000..eb7115c
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/exception.c
@@ -0,0 +1,239 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "exception.h"
+#include "hdfs.h"
+#include "jni_helper.h"
+#include "platform.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define EXCEPTION_INFO_LEN (sizeof(gExceptionInfo)/sizeof(gExceptionInfo[0]))
+
+struct ExceptionInfo {
+ const char * const name;
+ int noPrintFlag;
+ int excErrno;
+};
+
+static const struct ExceptionInfo gExceptionInfo[] = {
+ {
+ "java.io.FileNotFoundException",
+ NOPRINT_EXC_FILE_NOT_FOUND,
+ ENOENT,
+ },
+ {
+ "org.apache.hadoop.security.AccessControlException",
+ NOPRINT_EXC_ACCESS_CONTROL,
+ EACCES,
+ },
+ {
+ "org.apache.hadoop.fs.UnresolvedLinkException",
+ NOPRINT_EXC_UNRESOLVED_LINK,
+ ENOLINK,
+ },
+ {
+ "org.apache.hadoop.fs.ParentNotDirectoryException",
+ NOPRINT_EXC_PARENT_NOT_DIRECTORY,
+ ENOTDIR,
+ },
+ {
+ "java.lang.IllegalArgumentException",
+ NOPRINT_EXC_ILLEGAL_ARGUMENT,
+ EINVAL,
+ },
+ {
+ "java.lang.OutOfMemoryError",
+ 0,
+ ENOMEM,
+ },
+ {
+ "org.apache.hadoop.hdfs.server.namenode.SafeModeException",
+ 0,
+ EROFS,
+ },
+ {
+ "org.apache.hadoop.fs.FileAlreadyExistsException",
+ 0,
+ EEXIST,
+ },
+ {
+ "org.apache.hadoop.hdfs.protocol.QuotaExceededException",
+ 0,
+ EDQUOT,
+ },
+ {
+ "java.lang.UnsupportedOperationException",
+ 0,
+ ENOTSUP,
+ },
+ {
+ "org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException",
+ 0,
+ ESTALE,
+ },
+};
+
+void getExceptionInfo(const char *excName, int noPrintFlags,
+ int *excErrno, int *shouldPrint)
+{
+ int i;
+
+ for (i = 0; i < EXCEPTION_INFO_LEN; i++) {
+ if (strstr(gExceptionInfo[i].name, excName)) {
+ break;
+ }
+ }
+ if (i < EXCEPTION_INFO_LEN) {
+ *shouldPrint = !(gExceptionInfo[i].noPrintFlag & noPrintFlags);
+ *excErrno = gExceptionInfo[i].excErrno;
+ } else {
+ *shouldPrint = 1;
+ *excErrno = EINTERNAL;
+ }
+}
+
+int printExceptionAndFreeV(JNIEnv *env, jthrowable exc, int noPrintFlags,
+ const char *fmt, va_list ap)
+{
+ int i, noPrint, excErrno;
+ char *className = NULL;
+ jstring jStr = NULL;
+ jvalue jVal;
+ jthrowable jthr;
+ const char *stackTrace;
+
+ jthr = classNameOfObject(exc, env, &className);
+ if (jthr) {
+ fprintf(stderr, "PrintExceptionAndFree: error determining class name "
+ "of exception.\n");
+ className = strdup("(unknown)");
+ destroyLocalReference(env, jthr);
+ }
+ for (i = 0; i < EXCEPTION_INFO_LEN; i++) {
+ if (!strcmp(gExceptionInfo[i].name, className)) {
+ break;
+ }
+ }
+ if (i < EXCEPTION_INFO_LEN) {
+ noPrint = (gExceptionInfo[i].noPrintFlag & noPrintFlags);
+ excErrno = gExceptionInfo[i].excErrno;
+ } else {
+ noPrint = 0;
+ excErrno = EINTERNAL;
+ }
+ if (!noPrint) {
+ vfprintf(stderr, fmt, ap);
+ fprintf(stderr, " error:\n");
+
+ // We don't want to use ExceptionDescribe here, because that requires a
+ // pending exception. Instead, use ExceptionUtils.
+ jthr = invokeMethod(env, &jVal, STATIC, NULL,
+ "org/apache/commons/lang/exception/ExceptionUtils",
+ "getStackTrace", "(Ljava/lang/Throwable;)Ljava/lang/String;", exc);
+ if (jthr) {
+ fprintf(stderr, "(unable to get stack trace for %s exception: "
+ "ExceptionUtils::getStackTrace error.)\n", className);
+ destroyLocalReference(env, jthr);
+ } else {
+ jStr = jVal.l;
+ stackTrace = (*env)->GetStringUTFChars(env, jStr, NULL);
+ if (!stackTrace) {
+ fprintf(stderr, "(unable to get stack trace for %s exception: "
+ "GetStringUTFChars error.)\n", className);
+ } else {
+ fprintf(stderr, "%s", stackTrace);
+ (*env)->ReleaseStringUTFChars(env, jStr, stackTrace);
+ }
+ }
+ }
+ destroyLocalReference(env, jStr);
+ destroyLocalReference(env, exc);
+ free(className);
+ return excErrno;
+}
+
+int printExceptionAndFree(JNIEnv *env, jthrowable exc, int noPrintFlags,
+ const char *fmt, ...)
+{
+ va_list ap;
+ int ret;
+
+ va_start(ap, fmt);
+ ret = printExceptionAndFreeV(env, exc, noPrintFlags, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+int printPendingExceptionAndFree(JNIEnv *env, int noPrintFlags,
+ const char *fmt, ...)
+{
+ va_list ap;
+ int ret;
+ jthrowable exc;
+
+ exc = (*env)->ExceptionOccurred(env);
+ if (!exc) {
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fprintf(stderr, " error: (no exception)");
+ ret = 0;
+ } else {
+ (*env)->ExceptionClear(env);
+ va_start(ap, fmt);
+ ret = printExceptionAndFreeV(env, exc, noPrintFlags, fmt, ap);
+ va_end(ap);
+ }
+ return ret;
+}
+
+jthrowable getPendingExceptionAndClear(JNIEnv *env)
+{
+ jthrowable jthr = (*env)->ExceptionOccurred(env);
+ if (!jthr)
+ return NULL;
+ (*env)->ExceptionClear(env);
+ return jthr;
+}
+
+jthrowable newRuntimeError(JNIEnv *env, const char *fmt, ...)
+{
+ char buf[512];
+ jobject out, exc;
+ jstring jstr;
+ va_list ap;
+
+ va_start(ap, fmt);
+ vsnprintf(buf, sizeof(buf), fmt, ap);
+ va_end(ap);
+ jstr = (*env)->NewStringUTF(env, buf);
+ if (!jstr) {
+ // We got an out of memory exception rather than a RuntimeException.
+ // Too bad...
+ return getPendingExceptionAndClear(env);
+ }
+ exc = constructNewObjectOfClass(env, &out, "RuntimeException",
+ "(java/lang/String;)V", jstr);
+ (*env)->DeleteLocalRef(env, jstr);
+ // Again, we'll either get an out of memory exception or the
+ // RuntimeException we wanted.
+ return (exc) ? exc : out;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/exception.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/exception.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/exception.h
new file mode 100644
index 0000000..5fa7fa6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/exception.h
@@ -0,0 +1,157 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_EXCEPTION_H
+#define LIBHDFS_EXCEPTION_H
+
+/**
+ * Exception handling routines for libhdfs.
+ *
+ * The convention we follow here is to clear pending exceptions as soon as they
+ * are raised. Never assume that the caller of your function will clean up
+ * after you-- do it yourself. Unhandled exceptions can lead to memory leaks
+ * and other undefined behavior.
+ *
+ * If you encounter an exception, return a local reference to it. The caller is
+ * responsible for freeing the local reference, by calling a function like
+ * PrintExceptionAndFree. (You can also free exceptions directly by calling
+ * DeleteLocalRef. However, that would not produce an error message, so it's
+ * usually not what you want.)
+ */
+
+#include "platform.h"
+
+#include <jni.h>
+#include <stdio.h>
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <search.h>
+#include <errno.h>
+
+/**
+ * Exception noprint flags
+ *
+ * Theses flags determine which exceptions should NOT be printed to stderr by
+ * the exception printing routines. For example, if you expect to see
+ * FileNotFound, you might use NOPRINT_EXC_FILE_NOT_FOUND, to avoid filling the
+ * logs with messages about routine events.
+ *
+ * On the other hand, if you don't expect any failures, you might pass
+ * PRINT_EXC_ALL.
+ *
+ * You can OR these flags together to avoid printing multiple classes of
+ * exceptions.
+ */
+#define PRINT_EXC_ALL 0x00
+#define NOPRINT_EXC_FILE_NOT_FOUND 0x01
+#define NOPRINT_EXC_ACCESS_CONTROL 0x02
+#define NOPRINT_EXC_UNRESOLVED_LINK 0x04
+#define NOPRINT_EXC_PARENT_NOT_DIRECTORY 0x08
+#define NOPRINT_EXC_ILLEGAL_ARGUMENT 0x10
+
+/**
+ * Get information about an exception.
+ *
+ * @param excName The Exception name.
+ * This is a Java class name in JNI format.
+ * @param noPrintFlags Flags which determine which exceptions we should NOT
+ * print.
+ * @param excErrno (out param) The POSIX error number associated with the
+ * exception.
+ * @param shouldPrint (out param) Nonzero if we should print this exception,
+ * based on the noPrintFlags and its name.
+ */
+void getExceptionInfo(const char *excName, int noPrintFlags,
+ int *excErrno, int *shouldPrint);
+
+/**
+ * Print out information about an exception and free it.
+ *
+ * @param env The JNI environment
+ * @param exc The exception to print and free
+ * @param noPrintFlags Flags which determine which exceptions we should NOT
+ * print.
+ * @param fmt Printf-style format list
+ * @param ap Printf-style varargs
+ *
+ * @return The POSIX error number associated with the exception
+ * object.
+ */
+int printExceptionAndFreeV(JNIEnv *env, jthrowable exc, int noPrintFlags,
+ const char *fmt, va_list ap);
+
+/**
+ * Print out information about an exception and free it.
+ *
+ * @param env The JNI environment
+ * @param exc The exception to print and free
+ * @param noPrintFlags Flags which determine which exceptions we should NOT
+ * print.
+ * @param fmt Printf-style format list
+ * @param ... Printf-style varargs
+ *
+ * @return The POSIX error number associated with the exception
+ * object.
+ */
+int printExceptionAndFree(JNIEnv *env, jthrowable exc, int noPrintFlags,
+ const char *fmt, ...) TYPE_CHECKED_PRINTF_FORMAT(4, 5);
+
+/**
+ * Print out information about the pending exception and free it.
+ *
+ * @param env The JNI environment
+ * @param noPrintFlags Flags which determine which exceptions we should NOT
+ * print.
+ * @param fmt Printf-style format list
+ * @param ... Printf-style varargs
+ *
+ * @return The POSIX error number associated with the exception
+ * object.
+ */
+int printPendingExceptionAndFree(JNIEnv *env, int noPrintFlags,
+ const char *fmt, ...) TYPE_CHECKED_PRINTF_FORMAT(3, 4);
+
+/**
+ * Get a local reference to the pending exception and clear it.
+ *
+ * Once it is cleared, the exception will no longer be pending. The caller will
+ * have to decide what to do with the exception object.
+ *
+ * @param env The JNI environment
+ *
+ * @return The exception, or NULL if there was no exception
+ */
+jthrowable getPendingExceptionAndClear(JNIEnv *env);
+
+/**
+ * Create a new runtime error.
+ *
+ * This creates (but does not throw) a new RuntimeError.
+ *
+ * @param env The JNI environment
+ * @param fmt Printf-style format list
+ * @param ... Printf-style varargs
+ *
+ * @return A local reference to a RuntimeError
+ */
+jthrowable newRuntimeError(JNIEnv *env, const char *fmt, ...)
+ TYPE_CHECKED_PRINTF_FORMAT(2, 3);
+
+#undef TYPE_CHECKED_PRINTF_FORMAT
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/expect.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/expect.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/expect.c
new file mode 100644
index 0000000..576e9ef
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/expect.c
@@ -0,0 +1,68 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "expect.h"
+#include "hdfs.h"
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int expectFileStats(hdfsFile file,
+ uint64_t expectedTotalBytesRead,
+ uint64_t expectedTotalLocalBytesRead,
+ uint64_t expectedTotalShortCircuitBytesRead,
+ uint64_t expectedTotalZeroCopyBytesRead)
+{
+ struct hdfsReadStatistics *stats = NULL;
+ EXPECT_ZERO(hdfsFileGetReadStatistics(file, &stats));
+ fprintf(stderr, "expectFileStats(expectedTotalBytesRead=%"PRId64", "
+ "expectedTotalLocalBytesRead=%"PRId64", "
+ "expectedTotalShortCircuitBytesRead=%"PRId64", "
+ "expectedTotalZeroCopyBytesRead=%"PRId64", "
+ "totalBytesRead=%"PRId64", "
+ "totalLocalBytesRead=%"PRId64", "
+ "totalShortCircuitBytesRead=%"PRId64", "
+ "totalZeroCopyBytesRead=%"PRId64")\n",
+ expectedTotalBytesRead,
+ expectedTotalLocalBytesRead,
+ expectedTotalShortCircuitBytesRead,
+ expectedTotalZeroCopyBytesRead,
+ stats->totalBytesRead,
+ stats->totalLocalBytesRead,
+ stats->totalShortCircuitBytesRead,
+ stats->totalZeroCopyBytesRead);
+ if (expectedTotalBytesRead != UINT64_MAX) {
+ EXPECT_UINT64_EQ(expectedTotalBytesRead, stats->totalBytesRead);
+ }
+ if (expectedTotalLocalBytesRead != UINT64_MAX) {
+ EXPECT_UINT64_EQ(expectedTotalLocalBytesRead,
+ stats->totalLocalBytesRead);
+ }
+ if (expectedTotalShortCircuitBytesRead != UINT64_MAX) {
+ EXPECT_UINT64_EQ(expectedTotalShortCircuitBytesRead,
+ stats->totalShortCircuitBytesRead);
+ }
+ if (expectedTotalZeroCopyBytesRead != UINT64_MAX) {
+ EXPECT_UINT64_EQ(expectedTotalZeroCopyBytesRead,
+ stats->totalZeroCopyBytesRead);
+ }
+ hdfsFileFreeReadStatistics(stats);
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/expect.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/expect.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/expect.h
new file mode 100644
index 0000000..49aa285
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/expect.h
@@ -0,0 +1,179 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef LIBHDFS_NATIVE_TESTS_EXPECT_H
+#define LIBHDFS_NATIVE_TESTS_EXPECT_H
+
+#include <inttypes.h>
+#include <stdio.h>
+
+struct hdfsFile_internal;
+
+#define EXPECT_ZERO(x) \
+ do { \
+ int __my_ret__ = x; \
+ if (__my_ret__) { \
+ int __my_errno__ = errno; \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
+ "code %d (errno: %d): got nonzero from %s\n", \
+ __FILE__, __LINE__, __my_ret__, __my_errno__, #x); \
+ return __my_ret__; \
+ } \
+ } while (0);
+
+#define EXPECT_NULL(x) \
+ do { \
+ const void* __my_ret__ = x; \
+ int __my_errno__ = errno; \
+ if (__my_ret__ != NULL) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d (errno: %d): " \
+ "got non-NULL value %p from %s\n", \
+ __FILE__, __LINE__, __my_errno__, __my_ret__, #x); \
+ return -1; \
+ } \
+ } while (0);
+
+#define EXPECT_NULL_WITH_ERRNO(x, e) \
+ do { \
+ const void* __my_ret__ = x; \
+ int __my_errno__ = errno; \
+ if (__my_ret__ != NULL) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d (errno: %d): " \
+ "got non-NULL value %p from %s\n", \
+ __FILE__, __LINE__, __my_errno__, __my_ret__, #x); \
+ return -1; \
+ } \
+ if (__my_errno__ != e) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d (errno: %d): " \
+ "got expected NULL without expected errno %d from %s\n", \
+ __FILE__, __LINE__, __my_errno__, e, #x); \
+ return -1; \
+ } \
+ } while (0);
+
+#define EXPECT_NONNULL(x) \
+ do { \
+ const void* __my_ret__ = x; \
+ int __my_errno__ = errno; \
+ if (__my_ret__ == NULL) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d (errno: %d): " \
+ "got NULL from %s\n", __FILE__, __LINE__, __my_errno__, #x); \
+ return -1; \
+ } \
+ } while (0);
+
+#define EXPECT_NEGATIVE_ONE_WITH_ERRNO(x, e) \
+ do { \
+ int __my_ret__ = x; \
+ int __my_errno__ = errno; \
+ if (__my_ret__ != -1) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
+ "code %d (errno: %d): expected -1 from %s\n", \
+ __FILE__, __LINE__, \
+ __my_ret__, __my_errno__, #x); \
+ return -1; \
+ } \
+ if (__my_errno__ != e) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
+ "code %d (errno: %d): expected errno = %d from %s\n", \
+ __FILE__, __LINE__, __my_ret__, __my_errno__, e, #x); \
+ return -1; \
+ } \
+ } while (0);
+
+#define EXPECT_NONZERO(x) \
+ do { \
+ int __my_ret__ = x; \
+ int __my_errno__ = errno; \
+ if (!__my_ret__) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
+ "code %d (errno: %d): got zero from %s\n", __FILE__, __LINE__, \
+ __my_ret__, __my_errno__, #x); \
+ return -1; \
+ } \
+ } while (0);
+
+#define EXPECT_NONNEGATIVE(x) \
+ do { \
+ int __my_ret__ = x; \
+ int __my_errno__ = errno; \
+ if (__my_ret__ < 0) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
+ "code %d (errno: %d): got negative return from %s\n", \
+ __FILE__, __LINE__, __my_ret__, __my_errno__, #x); \
+ return __my_ret__; \
+ } \
+ } while (0);
+
+#define EXPECT_INT_EQ(x, y) \
+ do { \
+ int __my_ret__ = y; \
+ int __my_errno__ = errno; \
+ if (__my_ret__ != (x)) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
+ "code %d (errno: %d): expected %d\n", \
+ __FILE__, __LINE__, __my_ret__, __my_errno__, (x)); \
+ return -1; \
+ } \
+ } while (0);
+
+#define EXPECT_INT64_EQ(x, y) \
+ do { \
+ int64_t __my_ret__ = y; \
+ int __my_errno__ = errno; \
+ if (__my_ret__ != (x)) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
+ "value %"PRId64" (errno: %d): expected %"PRId64"\n", \
+ __FILE__, __LINE__, __my_ret__, __my_errno__, (x)); \
+ return -1; \
+ } \
+ } while (0);
+
+#define EXPECT_UINT64_EQ(x, y) \
+ do { \
+ uint64_t __my_ret__ = y; \
+ int __my_errno__ = errno; \
+ if (__my_ret__ != (x)) { \
+ fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
+ "value %"PRIu64" (errno: %d): expected %"PRIu64"\n", \
+ __FILE__, __LINE__, __my_ret__, __my_errno__, (x)); \
+ return -1; \
+ } \
+ } while (0);
+
+#define RETRY_ON_EINTR_GET_ERRNO(ret, expr) do { \
+ ret = expr; \
+ if (!ret) \
+ break; \
+ ret = -errno; \
+ } while (ret == -EINTR);
+
+/**
+ * Test that an HDFS file has the given statistics.
+ *
+ * Any parameter can be set to UINT64_MAX to avoid checking it.
+ *
+ * @return 0 on success; error code otherwise
+ */
+int expectFileStats(struct hdfsFile_internal *file,
+ uint64_t expectedTotalBytesRead,
+ uint64_t expectedTotalLocalBytesRead,
+ uint64_t expectedTotalShortCircuitBytesRead,
+ uint64_t expectedTotalZeroCopyBytesRead);
+
+#endif
[10/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/test_fuse_dfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/test_fuse_dfs.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/test_fuse_dfs.c
deleted file mode 100644
index f4212a6..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/test_fuse_dfs.c
+++ /dev/null
@@ -1,378 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse-dfs/test/fuse_workload.h"
-#include "libhdfs/expect.h"
-#include "libhdfs/hdfs.h"
-#include "libhdfs/native_mini_dfs.h"
-#include "util/posix_util.h"
-
-#include <ctype.h>
-#include <errno.h>
-#include <libgen.h>
-#include <limits.h>
-#include <mntent.h>
-#include <semaphore.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <time.h>
-#include <unistd.h>
-
-/** Exit status to return when there is an exec error.
- *
- * We assume that fusermount and fuse_dfs don't normally return this error code.
- */
-#define EXIT_STATUS_EXEC_ERROR 240
-
-/** Maximum number of times to try to unmount the fuse filesystem we created.
- */
-#define MAX_UNMOUNT_TRIES 20
-
-/**
- * Verify that the fuse workload works on the local FS.
- *
- * @return 0 on success; error code otherwise
- */
-static int verifyFuseWorkload(void)
-{
- char tempDir[PATH_MAX];
-
- EXPECT_ZERO(createTempDir(tempDir, sizeof(tempDir), 0755));
- EXPECT_ZERO(runFuseWorkload(tempDir, "test"));
- EXPECT_ZERO(recursiveDelete(tempDir));
-
- return 0;
-}
-
-static int fuserMount(int *procRet, ...) __attribute__((sentinel));
-
-/**
- * Invoke the fusermount binary.
- *
- * @param retVal (out param) The return value from fusermount
- *
- * @return 0 on success; error code if the fork fails
- */
-static int fuserMount(int *procRet, ...)
-{
- int ret, status;
- size_t i = 0;
- char *args[64], *c;
- va_list ap;
- pid_t pid, pret;
-
- args[i++] = "fusermount";
- va_start(ap, procRet);
- while (1) {
- c = va_arg(ap, char *);
- args[i++] = c;
- if (!c)
- break;
- if (i > sizeof(args)/sizeof(args[0])) {
- va_end(ap);
- return -EINVAL;
- }
- }
- va_end(ap);
- pid = fork();
- if (pid < 0) {
- ret = errno;
- fprintf(stderr, "FUSE_TEST: failed to fork: error %d: %s\n",
- ret, strerror(ret));
- return -ret;
- } else if (pid == 0) {
- if (execvp("fusermount", args)) {
- ret = errno;
- fprintf(stderr, "FUSE_TEST: failed to execute fusermount: "
- "error %d: %s\n", ret, strerror(ret));
- exit(EXIT_STATUS_EXEC_ERROR);
- }
- }
- pret = waitpid(pid, &status, 0);
- if (pret != pid) {
- ret = errno;
- fprintf(stderr, "FUSE_TEST: failed to wait for pid %d: returned %d "
- "(error %d: %s)\n", pid, pret, ret, strerror(ret));
- return -ret;
- }
- if (WIFEXITED(status)) {
- *procRet = WEXITSTATUS(status);
- } else if (WIFSIGNALED(status)) {
- fprintf(stderr, "FUSE_TEST: fusermount exited with signal %d\n",
- WTERMSIG(status));
- *procRet = -1;
- } else {
- fprintf(stderr, "FUSE_TEST: fusermount exited with unknown exit type\n");
- *procRet = -1;
- }
- return 0;
-}
-
-static int isMounted(const char *mntPoint)
-{
- int ret;
- FILE *fp;
- struct mntent *mntEnt;
-
- fp = setmntent("/proc/mounts", "r");
- if (!fp) {
- ret = errno;
- fprintf(stderr, "FUSE_TEST: isMounted(%s) failed to open /proc/mounts: "
- "error %d: %s", mntPoint, ret, strerror(ret));
- return -ret;
- }
- while ((mntEnt = getmntent(fp))) {
- if (!strcmp(mntEnt->mnt_dir, mntPoint)) {
- endmntent(fp);
- return 1;
- }
- }
- endmntent(fp);
- return 0;
-}
-
-static int waitForMount(const char *mntPoint, int retries)
-{
- int ret, try = 0;
-
- while (try++ < retries) {
- ret = isMounted(mntPoint);
- if (ret < 0) {
- fprintf(stderr, "FUSE_TEST: waitForMount(%s, %d): isMounted returned "
- "error %d\n", mntPoint, retries, ret);
- } else if (ret == 1) {
- return 0;
- }
- sleepNoSig(2);
- }
- return -ETIMEDOUT;
-}
-
-/**
- * Try to unmount the fuse filesystem we mounted.
- *
- * Normally, only one try should be sufficient to unmount the filesystem.
- * However, if our tests needs to exit right after starting the fuse_dfs process,
- * the fuse_dfs process might not have gotten around to mounting itself yet. The
- * retry loop in this function ensures that we always unmount FUSE before
- * exiting, rather than leaving around a zombie fuse_dfs.
- *
- * @param mntPoint Where the FUSE filesystem is mounted
- * @return 0 on success; error code otherwise
- */
-static int cleanupFuse(const char *mntPoint)
-{
- int ret, pret, tries = 0;
-
- while (1) {
- ret = fuserMount(&pret, "-u", mntPoint, NULL);
- if (ret) {
- fprintf(stderr, "FUSE_TEST: unmountFuse: failed to invoke fuserMount: "
- "error %d\n", ret);
- return ret;
- }
- if (pret == 0) {
- fprintf(stderr, "FUSE_TEST: successfully unmounted FUSE filesystem.\n");
- return 0;
- }
- if (tries++ > MAX_UNMOUNT_TRIES) {
- return -EIO;
- }
- fprintf(stderr, "FUSE_TEST: retrying unmount in 2 seconds...\n");
- sleepNoSig(2);
- }
-}
-
-/**
- * Create a fuse_dfs process using the miniDfsCluster we set up.
- *
- * @param argv0 argv[0], as passed into main
- * @param cluster The NativeMiniDfsCluster to connect to
- * @param mntPoint The mount point
- * @param pid (out param) the fuse_dfs process
- *
- * @return 0 on success; error code otherwise
- */
-static int spawnFuseServer(const char *argv0,
- const struct NativeMiniDfsCluster *cluster, const char *mntPoint,
- pid_t *pid)
-{
- int ret, procRet;
- char scratch[PATH_MAX], *dir, fusePath[PATH_MAX], portOpt[128];
-
- snprintf(scratch, sizeof(scratch), "%s", argv0);
- dir = dirname(scratch);
- snprintf(fusePath, sizeof(fusePath), "%s/fuse_dfs", dir);
- if (access(fusePath, X_OK)) {
- fprintf(stderr, "FUSE_TEST: spawnFuseServer: failed to find fuse_dfs "
- "binary at %s!\n", fusePath);
- return -ENOENT;
- }
- /* Let's make sure no other FUSE filesystem is mounted at mntPoint */
- ret = fuserMount(&procRet, "-u", mntPoint, NULL);
- if (ret) {
- fprintf(stderr, "FUSE_TEST: fuserMount -u %s failed with error %d\n",
- mntPoint, ret);
- return -EIO;
- }
- if (procRet == EXIT_STATUS_EXEC_ERROR) {
- fprintf(stderr, "FUSE_TEST: fuserMount probably could not be executed\n");
- return -EIO;
- }
- /* fork and exec the fuse_dfs process */
- *pid = fork();
- if (*pid < 0) {
- ret = errno;
- fprintf(stderr, "FUSE_TEST: spawnFuseServer: failed to fork: "
- "error %d: %s\n", ret, strerror(ret));
- return -ret;
- } else if (*pid == 0) {
- snprintf(portOpt, sizeof(portOpt), "-oport=%d",
- nmdGetNameNodePort(cluster));
- if (execl(fusePath, fusePath, "-obig_writes", "-oserver=hdfs://localhost",
- portOpt, "-onopermissions", "-ononempty", "-oinitchecks",
- mntPoint, "-f", NULL)) {
- ret = errno;
- fprintf(stderr, "FUSE_TEST: spawnFuseServer: failed to execv %s: "
- "error %d: %s\n", fusePath, ret, strerror(ret));
- exit(EXIT_STATUS_EXEC_ERROR);
- }
- }
- return 0;
-}
-
-/**
- * Test that we can start up fuse_dfs and do some stuff.
- */
-int main(int argc, char **argv)
-{
- int ret, pret, status;
- pid_t fusePid;
- const char *mntPoint;
- char mntTmp[PATH_MAX] = "";
- struct NativeMiniDfsCluster* tlhCluster;
- struct NativeMiniDfsConf conf = {
- .doFormat = 1,
- };
-
- mntPoint = getenv("TLH_FUSE_MNT_POINT");
- if (!mntPoint) {
- if (createTempDir(mntTmp, sizeof(mntTmp), 0755)) {
- fprintf(stderr, "FUSE_TEST: failed to create temporary directory for "
- "fuse mount point.\n");
- ret = EXIT_FAILURE;
- goto done;
- }
- fprintf(stderr, "FUSE_TEST: creating mount point at '%s'\n", mntTmp);
- mntPoint = mntTmp;
- }
- if (verifyFuseWorkload()) {
- fprintf(stderr, "FUSE_TEST: failed to verify fuse workload on "
- "local FS.\n");
- ret = EXIT_FAILURE;
- goto done_rmdir;
- }
- tlhCluster = nmdCreate(&conf);
- if (!tlhCluster) {
- ret = EXIT_FAILURE;
- goto done_rmdir;
- }
- if (nmdWaitClusterUp(tlhCluster)) {
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- ret = spawnFuseServer(argv[0], tlhCluster, mntPoint, &fusePid);
- if (ret) {
- fprintf(stderr, "FUSE_TEST: spawnFuseServer failed with error "
- "code %d\n", ret);
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- ret = waitForMount(mntPoint, 20);
- if (ret) {
- fprintf(stderr, "FUSE_TEST: waitForMount(%s) failed with error "
- "code %d\n", mntPoint, ret);
- cleanupFuse(mntPoint);
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- ret = runFuseWorkload(mntPoint, "test");
- if (ret) {
- fprintf(stderr, "FUSE_TEST: runFuseWorkload failed with error "
- "code %d\n", ret);
- cleanupFuse(mntPoint);
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- if (cleanupFuse(mntPoint)) {
- fprintf(stderr, "FUSE_TEST: fuserMount -u %s failed with error "
- "code %d\n", mntPoint, ret);
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- alarm(120);
- pret = waitpid(fusePid, &status, 0);
- if (pret != fusePid) {
- ret = errno;
- fprintf(stderr, "FUSE_TEST: failed to wait for fusePid %d: "
- "returned %d: error %d (%s)\n",
- fusePid, pret, ret, strerror(ret));
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- if (WIFEXITED(status)) {
- ret = WEXITSTATUS(status);
- if (ret) {
- fprintf(stderr, "FUSE_TEST: fuse exited with failure status "
- "%d!\n", ret);
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- } else if (WIFSIGNALED(status)) {
- ret = WTERMSIG(status);
- if (ret != SIGTERM) {
- fprintf(stderr, "FUSE_TEST: fuse exited with unexpected "
- "signal %d!\n", ret);
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- } else {
- fprintf(stderr, "FUSE_TEST: fusermount exited with unknown exit type\n");
- ret = EXIT_FAILURE;
- goto done_nmd_shutdown;
- }
- ret = EXIT_SUCCESS;
-
-done_nmd_shutdown:
- EXPECT_ZERO(nmdShutdown(tlhCluster));
- nmdFree(tlhCluster);
-done_rmdir:
- if (mntTmp[0]) {
- rmdir(mntTmp);
- }
-done:
- if (ret == EXIT_SUCCESS) {
- fprintf(stderr, "FUSE_TEST: SUCCESS.\n");
- } else {
- fprintf(stderr, "FUSE_TEST: FAILURE!\n");
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/common/htable.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/common/htable.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/common/htable.c
deleted file mode 100644
index 50c89ea..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/common/htable.c
+++ /dev/null
@@ -1,287 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "common/htable.h"
-
-#include <errno.h>
-#include <inttypes.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-struct htable_pair {
- void *key;
- void *val;
-};
-
-/**
- * A hash table which uses linear probing.
- */
-struct htable {
- uint32_t capacity;
- uint32_t used;
- htable_hash_fn_t hash_fun;
- htable_eq_fn_t eq_fun;
- struct htable_pair *elem;
-};
-
-/**
- * An internal function for inserting a value into the hash table.
- *
- * Note: this function assumes that you have made enough space in the table.
- *
- * @param nelem The new element to insert.
- * @param capacity The capacity of the hash table.
- * @param hash_fun The hash function to use.
- * @param key The key to insert.
- * @param val The value to insert.
- */
-static void htable_insert_internal(struct htable_pair *nelem,
- uint32_t capacity, htable_hash_fn_t hash_fun, void *key,
- void *val)
-{
- uint32_t i;
-
- i = hash_fun(key, capacity);
- while (1) {
- if (!nelem[i].key) {
- nelem[i].key = key;
- nelem[i].val = val;
- return;
- }
- i++;
- if (i == capacity) {
- i = 0;
- }
- }
-}
-
-static int htable_realloc(struct htable *htable, uint32_t new_capacity)
-{
- struct htable_pair *nelem;
- uint32_t i, old_capacity = htable->capacity;
- htable_hash_fn_t hash_fun = htable->hash_fun;
-
- nelem = calloc(new_capacity, sizeof(struct htable_pair));
- if (!nelem) {
- return ENOMEM;
- }
- for (i = 0; i < old_capacity; i++) {
- struct htable_pair *pair = htable->elem + i;
- if (pair->key) {
- htable_insert_internal(nelem, new_capacity, hash_fun,
- pair->key, pair->val);
- }
- }
- free(htable->elem);
- htable->elem = nelem;
- htable->capacity = new_capacity;
- return 0;
-}
-
-static uint32_t round_up_to_power_of_2(uint32_t i)
-{
- if (i == 0) {
- return 1;
- }
- i--;
- i |= i >> 1;
- i |= i >> 2;
- i |= i >> 4;
- i |= i >> 8;
- i |= i >> 16;
- i++;
- return i;
-}
-
-struct htable *htable_alloc(uint32_t size,
- htable_hash_fn_t hash_fun, htable_eq_fn_t eq_fun)
-{
- struct htable *htable;
-
- htable = calloc(1, sizeof(*htable));
- if (!htable) {
- return NULL;
- }
- size = round_up_to_power_of_2(size);
- if (size < HTABLE_MIN_SIZE) {
- size = HTABLE_MIN_SIZE;
- }
- htable->hash_fun = hash_fun;
- htable->eq_fun = eq_fun;
- htable->used = 0;
- if (htable_realloc(htable, size)) {
- free(htable);
- return NULL;
- }
- return htable;
-}
-
-void htable_visit(struct htable *htable, visitor_fn_t fun, void *ctx)
-{
- uint32_t i;
-
- for (i = 0; i != htable->capacity; ++i) {
- struct htable_pair *elem = htable->elem + i;
- if (elem->key) {
- fun(ctx, elem->key, elem->val);
- }
- }
-}
-
-void htable_free(struct htable *htable)
-{
- if (htable) {
- free(htable->elem);
- free(htable);
- }
-}
-
-int htable_put(struct htable *htable, void *key, void *val)
-{
- int ret;
- uint32_t nused;
-
- // NULL is not a valid key value.
- // This helps us implement htable_get_internal efficiently, since we know
- // that we can stop when we encounter the first NULL key.
- if (!key) {
- return EINVAL;
- }
- // NULL is not a valid value. Otherwise the results of htable_get would
- // be confusing (does a NULL return mean entry not found, or that the
- // entry was found and was NULL?)
- if (!val) {
- return EINVAL;
- }
- // Re-hash if we have used more than half of the hash table
- nused = htable->used + 1;
- if (nused >= (htable->capacity / 2)) {
- ret = htable_realloc(htable, htable->capacity * 2);
- if (ret)
- return ret;
- }
- htable_insert_internal(htable->elem, htable->capacity,
- htable->hash_fun, key, val);
- htable->used++;
- return 0;
-}
-
-static int htable_get_internal(const struct htable *htable,
- const void *key, uint32_t *out)
-{
- uint32_t start_idx, idx;
-
- start_idx = htable->hash_fun(key, htable->capacity);
- idx = start_idx;
- while (1) {
- struct htable_pair *pair = htable->elem + idx;
- if (!pair->key) {
- // We always maintain the invariant that the entries corresponding
- // to a given key are stored in a contiguous block, not separated
- // by any NULLs. So if we encounter a NULL, our search is over.
- return ENOENT;
- } else if (htable->eq_fun(pair->key, key)) {
- *out = idx;
- return 0;
- }
- idx++;
- if (idx == htable->capacity) {
- idx = 0;
- }
- if (idx == start_idx) {
- return ENOENT;
- }
- }
-}
-
-void *htable_get(const struct htable *htable, const void *key)
-{
- uint32_t idx;
-
- if (htable_get_internal(htable, key, &idx)) {
- return NULL;
- }
- return htable->elem[idx].val;
-}
-
-void htable_pop(struct htable *htable, const void *key,
- void **found_key, void **found_val)
-{
- uint32_t hole, i;
- const void *nkey;
-
- if (htable_get_internal(htable, key, &hole)) {
- *found_key = NULL;
- *found_val = NULL;
- return;
- }
- i = hole;
- htable->used--;
- // We need to maintain the compactness invariant used in
- // htable_get_internal. This invariant specifies that the entries for any
- // given key are never separated by NULLs (although they may be separated
- // by entries for other keys.)
- while (1) {
- i++;
- if (i == htable->capacity) {
- i = 0;
- }
- nkey = htable->elem[i].key;
- if (!nkey) {
- *found_key = htable->elem[hole].key;
- *found_val = htable->elem[hole].val;
- htable->elem[hole].key = NULL;
- htable->elem[hole].val = NULL;
- return;
- } else if (htable->eq_fun(key, nkey)) {
- htable->elem[hole].key = htable->elem[i].key;
- htable->elem[hole].val = htable->elem[i].val;
- hole = i;
- }
- }
-}
-
-uint32_t htable_used(const struct htable *htable)
-{
- return htable->used;
-}
-
-uint32_t htable_capacity(const struct htable *htable)
-{
- return htable->capacity;
-}
-
-uint32_t ht_hash_string(const void *str, uint32_t max)
-{
- const char *s = str;
- uint32_t hash = 0;
-
- while (*s) {
- hash = (hash * 31) + *s;
- s++;
- }
- return hash % max;
-}
-
-int ht_compare_string(const void *a, const void *b)
-{
- return strcmp(a, b) == 0;
-}
-
-// vim: ts=4:sw=4:tw=79:et
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/common/htable.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/common/htable.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/common/htable.h
deleted file mode 100644
index 33f1229..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/common/htable.h
+++ /dev/null
@@ -1,161 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef HADOOP_CORE_COMMON_HASH_TABLE
-#define HADOOP_CORE_COMMON_HASH_TABLE
-
-#include <inttypes.h>
-#include <stdio.h>
-#include <stdint.h>
-
-#define HTABLE_MIN_SIZE 4
-
-struct htable;
-
-/**
- * An HTable hash function.
- *
- * @param key The key.
- * @param capacity The total capacity.
- *
- * @return The hash slot. Must be less than the capacity.
- */
-typedef uint32_t (*htable_hash_fn_t)(const void *key, uint32_t capacity);
-
-/**
- * An HTable equality function. Compares two keys.
- *
- * @param a First key.
- * @param b Second key.
- *
- * @return nonzero if the keys are equal.
- */
-typedef int (*htable_eq_fn_t)(const void *a, const void *b);
-
-/**
- * Allocate a new hash table.
- *
- * @param capacity The minimum suggested starting capacity.
- * @param hash_fun The hash function to use in this hash table.
- * @param eq_fun The equals function to use in this hash table.
- *
- * @return The new hash table on success; NULL on OOM.
- */
-struct htable *htable_alloc(uint32_t capacity, htable_hash_fn_t hash_fun,
- htable_eq_fn_t eq_fun);
-
-typedef void (*visitor_fn_t)(void *ctx, void *key, void *val);
-
-/**
- * Visit all of the entries in the hash table.
- *
- * @param htable The hash table.
- * @param fun The callback function to invoke on each key and value.
- * @param ctx Context pointer to pass to the callback.
- */
-void htable_visit(struct htable *htable, visitor_fn_t fun, void *ctx);
-
-/**
- * Free the hash table.
- *
- * It is up the calling code to ensure that the keys and values inside the
- * table are de-allocated, if that is necessary.
- *
- * @param htable The hash table.
- */
-void htable_free(struct htable *htable);
-
-/**
- * Add an entry to the hash table.
- *
- * @param htable The hash table.
- * @param key The key to add. This cannot be NULL.
- * @param fun The value to add. This cannot be NULL.
- *
- * @return 0 on success;
- * EEXIST if the value already exists in the table;
- * ENOMEM if there is not enough memory to add the element.
- * EFBIG if the hash table has too many entries to fit in 32
- * bits.
- */
-int htable_put(struct htable *htable, void *key, void *val);
-
-/**
- * Get an entry from the hash table.
- *
- * @param htable The hash table.
- * @param key The key to find.
- *
- * @return NULL if there is no such entry; the entry otherwise.
- */
-void *htable_get(const struct htable *htable, const void *key);
-
-/**
- * Get an entry from the hash table and remove it.
- *
- * @param htable The hash table.
- * @param key The key for the entry find and remove.
- * @param found_key (out param) NULL if the entry was not found; the found key
- * otherwise.
- * @param found_val (out param) NULL if the entry was not found; the found
- * value otherwise.
- */
-void htable_pop(struct htable *htable, const void *key,
- void **found_key, void **found_val);
-
-/**
- * Get the number of entries used in the hash table.
- *
- * @param htable The hash table.
- *
- * @return The number of entries used in the hash table.
- */
-uint32_t htable_used(const struct htable *htable);
-
-/**
- * Get the capacity of the hash table.
- *
- * @param htable The hash table.
- *
- * @return The capacity of the hash table.
- */
-uint32_t htable_capacity(const struct htable *htable);
-
-/**
- * Hash a string.
- *
- * @param str The string.
- * @param max Maximum hash value
- *
- * @return A number less than max.
- */
-uint32_t ht_hash_string(const void *str, uint32_t max);
-
-/**
- * Compare two strings.
- *
- * @param a The first string.
- * @param b The second string.
- *
- * @return 1 if the strings are identical; 0 otherwise.
- */
-int ht_compare_string(const void *a, const void *b);
-
-#endif
-
-// vim: ts=4:sw=4:tw=79:et
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/exception.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/exception.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/exception.c
deleted file mode 100644
index eb7115c..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/exception.c
+++ /dev/null
@@ -1,239 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "exception.h"
-#include "hdfs.h"
-#include "jni_helper.h"
-#include "platform.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define EXCEPTION_INFO_LEN (sizeof(gExceptionInfo)/sizeof(gExceptionInfo[0]))
-
-struct ExceptionInfo {
- const char * const name;
- int noPrintFlag;
- int excErrno;
-};
-
-static const struct ExceptionInfo gExceptionInfo[] = {
- {
- "java.io.FileNotFoundException",
- NOPRINT_EXC_FILE_NOT_FOUND,
- ENOENT,
- },
- {
- "org.apache.hadoop.security.AccessControlException",
- NOPRINT_EXC_ACCESS_CONTROL,
- EACCES,
- },
- {
- "org.apache.hadoop.fs.UnresolvedLinkException",
- NOPRINT_EXC_UNRESOLVED_LINK,
- ENOLINK,
- },
- {
- "org.apache.hadoop.fs.ParentNotDirectoryException",
- NOPRINT_EXC_PARENT_NOT_DIRECTORY,
- ENOTDIR,
- },
- {
- "java.lang.IllegalArgumentException",
- NOPRINT_EXC_ILLEGAL_ARGUMENT,
- EINVAL,
- },
- {
- "java.lang.OutOfMemoryError",
- 0,
- ENOMEM,
- },
- {
- "org.apache.hadoop.hdfs.server.namenode.SafeModeException",
- 0,
- EROFS,
- },
- {
- "org.apache.hadoop.fs.FileAlreadyExistsException",
- 0,
- EEXIST,
- },
- {
- "org.apache.hadoop.hdfs.protocol.QuotaExceededException",
- 0,
- EDQUOT,
- },
- {
- "java.lang.UnsupportedOperationException",
- 0,
- ENOTSUP,
- },
- {
- "org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException",
- 0,
- ESTALE,
- },
-};
-
-void getExceptionInfo(const char *excName, int noPrintFlags,
- int *excErrno, int *shouldPrint)
-{
- int i;
-
- for (i = 0; i < EXCEPTION_INFO_LEN; i++) {
- if (strstr(gExceptionInfo[i].name, excName)) {
- break;
- }
- }
- if (i < EXCEPTION_INFO_LEN) {
- *shouldPrint = !(gExceptionInfo[i].noPrintFlag & noPrintFlags);
- *excErrno = gExceptionInfo[i].excErrno;
- } else {
- *shouldPrint = 1;
- *excErrno = EINTERNAL;
- }
-}
-
-int printExceptionAndFreeV(JNIEnv *env, jthrowable exc, int noPrintFlags,
- const char *fmt, va_list ap)
-{
- int i, noPrint, excErrno;
- char *className = NULL;
- jstring jStr = NULL;
- jvalue jVal;
- jthrowable jthr;
- const char *stackTrace;
-
- jthr = classNameOfObject(exc, env, &className);
- if (jthr) {
- fprintf(stderr, "PrintExceptionAndFree: error determining class name "
- "of exception.\n");
- className = strdup("(unknown)");
- destroyLocalReference(env, jthr);
- }
- for (i = 0; i < EXCEPTION_INFO_LEN; i++) {
- if (!strcmp(gExceptionInfo[i].name, className)) {
- break;
- }
- }
- if (i < EXCEPTION_INFO_LEN) {
- noPrint = (gExceptionInfo[i].noPrintFlag & noPrintFlags);
- excErrno = gExceptionInfo[i].excErrno;
- } else {
- noPrint = 0;
- excErrno = EINTERNAL;
- }
- if (!noPrint) {
- vfprintf(stderr, fmt, ap);
- fprintf(stderr, " error:\n");
-
- // We don't want to use ExceptionDescribe here, because that requires a
- // pending exception. Instead, use ExceptionUtils.
- jthr = invokeMethod(env, &jVal, STATIC, NULL,
- "org/apache/commons/lang/exception/ExceptionUtils",
- "getStackTrace", "(Ljava/lang/Throwable;)Ljava/lang/String;", exc);
- if (jthr) {
- fprintf(stderr, "(unable to get stack trace for %s exception: "
- "ExceptionUtils::getStackTrace error.)\n", className);
- destroyLocalReference(env, jthr);
- } else {
- jStr = jVal.l;
- stackTrace = (*env)->GetStringUTFChars(env, jStr, NULL);
- if (!stackTrace) {
- fprintf(stderr, "(unable to get stack trace for %s exception: "
- "GetStringUTFChars error.)\n", className);
- } else {
- fprintf(stderr, "%s", stackTrace);
- (*env)->ReleaseStringUTFChars(env, jStr, stackTrace);
- }
- }
- }
- destroyLocalReference(env, jStr);
- destroyLocalReference(env, exc);
- free(className);
- return excErrno;
-}
-
-int printExceptionAndFree(JNIEnv *env, jthrowable exc, int noPrintFlags,
- const char *fmt, ...)
-{
- va_list ap;
- int ret;
-
- va_start(ap, fmt);
- ret = printExceptionAndFreeV(env, exc, noPrintFlags, fmt, ap);
- va_end(ap);
- return ret;
-}
-
-int printPendingExceptionAndFree(JNIEnv *env, int noPrintFlags,
- const char *fmt, ...)
-{
- va_list ap;
- int ret;
- jthrowable exc;
-
- exc = (*env)->ExceptionOccurred(env);
- if (!exc) {
- va_start(ap, fmt);
- vfprintf(stderr, fmt, ap);
- va_end(ap);
- fprintf(stderr, " error: (no exception)");
- ret = 0;
- } else {
- (*env)->ExceptionClear(env);
- va_start(ap, fmt);
- ret = printExceptionAndFreeV(env, exc, noPrintFlags, fmt, ap);
- va_end(ap);
- }
- return ret;
-}
-
-jthrowable getPendingExceptionAndClear(JNIEnv *env)
-{
- jthrowable jthr = (*env)->ExceptionOccurred(env);
- if (!jthr)
- return NULL;
- (*env)->ExceptionClear(env);
- return jthr;
-}
-
-jthrowable newRuntimeError(JNIEnv *env, const char *fmt, ...)
-{
- char buf[512];
- jobject out, exc;
- jstring jstr;
- va_list ap;
-
- va_start(ap, fmt);
- vsnprintf(buf, sizeof(buf), fmt, ap);
- va_end(ap);
- jstr = (*env)->NewStringUTF(env, buf);
- if (!jstr) {
- // We got an out of memory exception rather than a RuntimeException.
- // Too bad...
- return getPendingExceptionAndClear(env);
- }
- exc = constructNewObjectOfClass(env, &out, "RuntimeException",
- "(java/lang/String;)V", jstr);
- (*env)->DeleteLocalRef(env, jstr);
- // Again, we'll either get an out of memory exception or the
- // RuntimeException we wanted.
- return (exc) ? exc : out;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/exception.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/exception.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/exception.h
deleted file mode 100644
index 5fa7fa6..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/exception.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_EXCEPTION_H
-#define LIBHDFS_EXCEPTION_H
-
-/**
- * Exception handling routines for libhdfs.
- *
- * The convention we follow here is to clear pending exceptions as soon as they
- * are raised. Never assume that the caller of your function will clean up
- * after you-- do it yourself. Unhandled exceptions can lead to memory leaks
- * and other undefined behavior.
- *
- * If you encounter an exception, return a local reference to it. The caller is
- * responsible for freeing the local reference, by calling a function like
- * PrintExceptionAndFree. (You can also free exceptions directly by calling
- * DeleteLocalRef. However, that would not produce an error message, so it's
- * usually not what you want.)
- */
-
-#include "platform.h"
-
-#include <jni.h>
-#include <stdio.h>
-
-#include <stdlib.h>
-#include <stdarg.h>
-#include <search.h>
-#include <errno.h>
-
-/**
- * Exception noprint flags
- *
- * Theses flags determine which exceptions should NOT be printed to stderr by
- * the exception printing routines. For example, if you expect to see
- * FileNotFound, you might use NOPRINT_EXC_FILE_NOT_FOUND, to avoid filling the
- * logs with messages about routine events.
- *
- * On the other hand, if you don't expect any failures, you might pass
- * PRINT_EXC_ALL.
- *
- * You can OR these flags together to avoid printing multiple classes of
- * exceptions.
- */
-#define PRINT_EXC_ALL 0x00
-#define NOPRINT_EXC_FILE_NOT_FOUND 0x01
-#define NOPRINT_EXC_ACCESS_CONTROL 0x02
-#define NOPRINT_EXC_UNRESOLVED_LINK 0x04
-#define NOPRINT_EXC_PARENT_NOT_DIRECTORY 0x08
-#define NOPRINT_EXC_ILLEGAL_ARGUMENT 0x10
-
-/**
- * Get information about an exception.
- *
- * @param excName The Exception name.
- * This is a Java class name in JNI format.
- * @param noPrintFlags Flags which determine which exceptions we should NOT
- * print.
- * @param excErrno (out param) The POSIX error number associated with the
- * exception.
- * @param shouldPrint (out param) Nonzero if we should print this exception,
- * based on the noPrintFlags and its name.
- */
-void getExceptionInfo(const char *excName, int noPrintFlags,
- int *excErrno, int *shouldPrint);
-
-/**
- * Print out information about an exception and free it.
- *
- * @param env The JNI environment
- * @param exc The exception to print and free
- * @param noPrintFlags Flags which determine which exceptions we should NOT
- * print.
- * @param fmt Printf-style format list
- * @param ap Printf-style varargs
- *
- * @return The POSIX error number associated with the exception
- * object.
- */
-int printExceptionAndFreeV(JNIEnv *env, jthrowable exc, int noPrintFlags,
- const char *fmt, va_list ap);
-
-/**
- * Print out information about an exception and free it.
- *
- * @param env The JNI environment
- * @param exc The exception to print and free
- * @param noPrintFlags Flags which determine which exceptions we should NOT
- * print.
- * @param fmt Printf-style format list
- * @param ... Printf-style varargs
- *
- * @return The POSIX error number associated with the exception
- * object.
- */
-int printExceptionAndFree(JNIEnv *env, jthrowable exc, int noPrintFlags,
- const char *fmt, ...) TYPE_CHECKED_PRINTF_FORMAT(4, 5);
-
-/**
- * Print out information about the pending exception and free it.
- *
- * @param env The JNI environment
- * @param noPrintFlags Flags which determine which exceptions we should NOT
- * print.
- * @param fmt Printf-style format list
- * @param ... Printf-style varargs
- *
- * @return The POSIX error number associated with the exception
- * object.
- */
-int printPendingExceptionAndFree(JNIEnv *env, int noPrintFlags,
- const char *fmt, ...) TYPE_CHECKED_PRINTF_FORMAT(3, 4);
-
-/**
- * Get a local reference to the pending exception and clear it.
- *
- * Once it is cleared, the exception will no longer be pending. The caller will
- * have to decide what to do with the exception object.
- *
- * @param env The JNI environment
- *
- * @return The exception, or NULL if there was no exception
- */
-jthrowable getPendingExceptionAndClear(JNIEnv *env);
-
-/**
- * Create a new runtime error.
- *
- * This creates (but does not throw) a new RuntimeError.
- *
- * @param env The JNI environment
- * @param fmt Printf-style format list
- * @param ... Printf-style varargs
- *
- * @return A local reference to a RuntimeError
- */
-jthrowable newRuntimeError(JNIEnv *env, const char *fmt, ...)
- TYPE_CHECKED_PRINTF_FORMAT(2, 3);
-
-#undef TYPE_CHECKED_PRINTF_FORMAT
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/expect.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/expect.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/expect.c
deleted file mode 100644
index 576e9ef..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/expect.c
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "expect.h"
-#include "hdfs.h"
-
-#include <inttypes.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-int expectFileStats(hdfsFile file,
- uint64_t expectedTotalBytesRead,
- uint64_t expectedTotalLocalBytesRead,
- uint64_t expectedTotalShortCircuitBytesRead,
- uint64_t expectedTotalZeroCopyBytesRead)
-{
- struct hdfsReadStatistics *stats = NULL;
- EXPECT_ZERO(hdfsFileGetReadStatistics(file, &stats));
- fprintf(stderr, "expectFileStats(expectedTotalBytesRead=%"PRId64", "
- "expectedTotalLocalBytesRead=%"PRId64", "
- "expectedTotalShortCircuitBytesRead=%"PRId64", "
- "expectedTotalZeroCopyBytesRead=%"PRId64", "
- "totalBytesRead=%"PRId64", "
- "totalLocalBytesRead=%"PRId64", "
- "totalShortCircuitBytesRead=%"PRId64", "
- "totalZeroCopyBytesRead=%"PRId64")\n",
- expectedTotalBytesRead,
- expectedTotalLocalBytesRead,
- expectedTotalShortCircuitBytesRead,
- expectedTotalZeroCopyBytesRead,
- stats->totalBytesRead,
- stats->totalLocalBytesRead,
- stats->totalShortCircuitBytesRead,
- stats->totalZeroCopyBytesRead);
- if (expectedTotalBytesRead != UINT64_MAX) {
- EXPECT_UINT64_EQ(expectedTotalBytesRead, stats->totalBytesRead);
- }
- if (expectedTotalLocalBytesRead != UINT64_MAX) {
- EXPECT_UINT64_EQ(expectedTotalLocalBytesRead,
- stats->totalLocalBytesRead);
- }
- if (expectedTotalShortCircuitBytesRead != UINT64_MAX) {
- EXPECT_UINT64_EQ(expectedTotalShortCircuitBytesRead,
- stats->totalShortCircuitBytesRead);
- }
- if (expectedTotalZeroCopyBytesRead != UINT64_MAX) {
- EXPECT_UINT64_EQ(expectedTotalZeroCopyBytesRead,
- stats->totalZeroCopyBytesRead);
- }
- hdfsFileFreeReadStatistics(stats);
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/expect.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/expect.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/expect.h
deleted file mode 100644
index 49aa285..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/expect.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_NATIVE_TESTS_EXPECT_H
-#define LIBHDFS_NATIVE_TESTS_EXPECT_H
-
-#include <inttypes.h>
-#include <stdio.h>
-
-struct hdfsFile_internal;
-
-#define EXPECT_ZERO(x) \
- do { \
- int __my_ret__ = x; \
- if (__my_ret__) { \
- int __my_errno__ = errno; \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
- "code %d (errno: %d): got nonzero from %s\n", \
- __FILE__, __LINE__, __my_ret__, __my_errno__, #x); \
- return __my_ret__; \
- } \
- } while (0);
-
-#define EXPECT_NULL(x) \
- do { \
- const void* __my_ret__ = x; \
- int __my_errno__ = errno; \
- if (__my_ret__ != NULL) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d (errno: %d): " \
- "got non-NULL value %p from %s\n", \
- __FILE__, __LINE__, __my_errno__, __my_ret__, #x); \
- return -1; \
- } \
- } while (0);
-
-#define EXPECT_NULL_WITH_ERRNO(x, e) \
- do { \
- const void* __my_ret__ = x; \
- int __my_errno__ = errno; \
- if (__my_ret__ != NULL) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d (errno: %d): " \
- "got non-NULL value %p from %s\n", \
- __FILE__, __LINE__, __my_errno__, __my_ret__, #x); \
- return -1; \
- } \
- if (__my_errno__ != e) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d (errno: %d): " \
- "got expected NULL without expected errno %d from %s\n", \
- __FILE__, __LINE__, __my_errno__, e, #x); \
- return -1; \
- } \
- } while (0);
-
-#define EXPECT_NONNULL(x) \
- do { \
- const void* __my_ret__ = x; \
- int __my_errno__ = errno; \
- if (__my_ret__ == NULL) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d (errno: %d): " \
- "got NULL from %s\n", __FILE__, __LINE__, __my_errno__, #x); \
- return -1; \
- } \
- } while (0);
-
-#define EXPECT_NEGATIVE_ONE_WITH_ERRNO(x, e) \
- do { \
- int __my_ret__ = x; \
- int __my_errno__ = errno; \
- if (__my_ret__ != -1) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
- "code %d (errno: %d): expected -1 from %s\n", \
- __FILE__, __LINE__, \
- __my_ret__, __my_errno__, #x); \
- return -1; \
- } \
- if (__my_errno__ != e) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
- "code %d (errno: %d): expected errno = %d from %s\n", \
- __FILE__, __LINE__, __my_ret__, __my_errno__, e, #x); \
- return -1; \
- } \
- } while (0);
-
-#define EXPECT_NONZERO(x) \
- do { \
- int __my_ret__ = x; \
- int __my_errno__ = errno; \
- if (!__my_ret__) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
- "code %d (errno: %d): got zero from %s\n", __FILE__, __LINE__, \
- __my_ret__, __my_errno__, #x); \
- return -1; \
- } \
- } while (0);
-
-#define EXPECT_NONNEGATIVE(x) \
- do { \
- int __my_ret__ = x; \
- int __my_errno__ = errno; \
- if (__my_ret__ < 0) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
- "code %d (errno: %d): got negative return from %s\n", \
- __FILE__, __LINE__, __my_ret__, __my_errno__, #x); \
- return __my_ret__; \
- } \
- } while (0);
-
-#define EXPECT_INT_EQ(x, y) \
- do { \
- int __my_ret__ = y; \
- int __my_errno__ = errno; \
- if (__my_ret__ != (x)) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
- "code %d (errno: %d): expected %d\n", \
- __FILE__, __LINE__, __my_ret__, __my_errno__, (x)); \
- return -1; \
- } \
- } while (0);
-
-#define EXPECT_INT64_EQ(x, y) \
- do { \
- int64_t __my_ret__ = y; \
- int __my_errno__ = errno; \
- if (__my_ret__ != (x)) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
- "value %"PRId64" (errno: %d): expected %"PRId64"\n", \
- __FILE__, __LINE__, __my_ret__, __my_errno__, (x)); \
- return -1; \
- } \
- } while (0);
-
-#define EXPECT_UINT64_EQ(x, y) \
- do { \
- uint64_t __my_ret__ = y; \
- int __my_errno__ = errno; \
- if (__my_ret__ != (x)) { \
- fprintf(stderr, "TEST_ERROR: failed on %s:%d with return " \
- "value %"PRIu64" (errno: %d): expected %"PRIu64"\n", \
- __FILE__, __LINE__, __my_ret__, __my_errno__, (x)); \
- return -1; \
- } \
- } while (0);
-
-#define RETRY_ON_EINTR_GET_ERRNO(ret, expr) do { \
- ret = expr; \
- if (!ret) \
- break; \
- ret = -errno; \
- } while (ret == -EINTR);
-
-/**
- * Test that an HDFS file has the given statistics.
- *
- * Any parameter can be set to UINT64_MAX to avoid checking it.
- *
- * @return 0 on success; error code otherwise
- */
-int expectFileStats(struct hdfsFile_internal *file,
- uint64_t expectedTotalBytesRead,
- uint64_t expectedTotalLocalBytesRead,
- uint64_t expectedTotalShortCircuitBytesRead,
- uint64_t expectedTotalZeroCopyBytesRead);
-
-#endif
[02/35] hadoop git commit: YARN-4228. FileSystemRMStateStore use
IOUtils#close instead of fs#close. (Bibin A Chundatt via rohithsharmaks)
Posted by ji...@apache.org.
YARN-4228. FileSystemRMStateStore use IOUtils#close instead of fs#close. (Bibin A Chundatt via rohithsharmaks)
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/3793cbe4
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/3793cbe4
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/3793cbe4
Branch: refs/heads/HDFS-8966
Commit: 3793cbe4c3cce5d03c4a18d562cbcb7cacd8f743
Parents: 9156fc6
Author: Rohith Sharma K S <ro...@apache.org>
Authored: Wed Oct 7 10:12:14 2015 +0530
Committer: Rohith Sharma K S <ro...@apache.org>
Committed: Wed Oct 7 10:12:14 2015 +0530
----------------------------------------------------------------------
hadoop-yarn-project/CHANGES.txt | 2 ++
.../server/resourcemanager/recovery/FileSystemRMStateStore.java | 2 +-
2 files changed, 3 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3793cbe4/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index de81879..d5e6920 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -919,6 +919,8 @@ Release 2.8.0 - UNRELEASED
YARN-4141. Runtime Application Priority change should not throw exception
for applications at finishing states (Sunil G via jlowe)
+ YARN-4228. FileSystemRMStateStore use IOUtils#close instead of fs#close. (Bibin A Chundatt via rohithsharmaks)
+
Release 2.7.2 - UNRELEASED
INCOMPATIBLE CHANGES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3793cbe4/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
index 5ee4709..f02fe78 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
@@ -718,7 +718,7 @@ public class FileSystemRMStateStore extends RMStateStore {
new FSAction<Void>() {
@Override
public Void run() throws Exception {
- fs.close();
+ IOUtils.closeStream(fs);
return null;
}
}.runWithRetries();
[11/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_statfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_statfs.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_statfs.c
deleted file mode 100644
index c9306a2..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_statfs.c
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_connect.h"
-
-
-int dfs_statfs(const char *path, struct statvfs *st)
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
- int ret;
-
- TRACE1("statfs",path)
-
- assert(path);
- assert(st);
- assert(dfs);
-
- memset(st,0,sizeof(struct statvfs));
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
-
- const tOffset cap = hdfsGetCapacity(fs);
- const tOffset used = hdfsGetUsed(fs);
- const tOffset bsize = hdfsGetDefaultBlockSize(fs);
-
- st->f_bsize = bsize;
- st->f_frsize = bsize;
- st->f_blocks = cap/bsize;
- st->f_bfree = (cap-used)/bsize;
- st->f_bavail = (cap-used)/bsize;
- st->f_files = 1000;
- st->f_ffree = 500;
- st->f_favail = 500;
- st->f_fsid = 1023;
- st->f_flag = ST_RDONLY | ST_NOSUID;
- st->f_namemax = 1023;
- ret = 0;
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_symlink.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_symlink.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_symlink.c
deleted file mode 100644
index be6e7eb..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_symlink.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-
-
-int dfs_symlink(const char *from, const char *to)
-{
- TRACE1("symlink", from)
- (void)from;
- (void)to;
- // bugbug we need the FileSystem to support this posix API
- return -ENOTSUP;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_truncate.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_truncate.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_truncate.c
deleted file mode 100644
index bf72ca6..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_truncate.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_connect.h"
-
-/**
- * For now implement truncate here and only for size == 0.
- * Weak implementation in that we just delete the file and
- * then re-create it, but don't set the user, group, and times to the old
- * file's metadata.
- */
-int dfs_truncate(const char *path, off_t size)
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- TRACE1("truncate", path)
-
- assert(path);
- assert('/' == *path);
- assert(dfs);
-
- if (size != 0) {
- return 0;
- }
-
- int ret = dfs_unlink(path);
- if (ret != 0) {
- return ret;
- }
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
-
- int flags = O_WRONLY | O_CREAT;
-
- hdfsFile file;
- if ((file = (hdfsFile)hdfsOpenFile(fs, path, flags, 0, 0, 0)) == NULL) {
- ERROR("Could not connect open file %s", path);
- ret = -EIO;
- goto cleanup;
- }
-
- if (hdfsCloseFile(fs, file) != 0) {
- ERROR("Could not close file %s", path);
- ret = -EIO;
- goto cleanup;
- }
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_unlink.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_unlink.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_unlink.c
deleted file mode 100644
index 45a4501..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_unlink.c
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_connect.h"
-#include "fuse_trash.h"
-
-int dfs_unlink(const char *path)
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- int ret = 0;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- TRACE1("unlink", path)
-
- assert(path);
- assert(dfs);
- assert('/' == *path);
-
- if (is_protected(path)) {
- ERROR("Trying to delete protected directory %s", path);
- ret = -EACCES;
- goto cleanup;
- }
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
-
- if (hdfsDeleteWithTrash(fs, path, dfs->usetrash)) {
- ERROR("Could not delete file %s", path);
- ret = (errno > 0) ? -errno : -EIO;
- goto cleanup;
- }
- ret = 0;
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_utimens.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_utimens.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_utimens.c
deleted file mode 100644
index dccff92..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_utimens.c
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_connect.h"
-
-int dfs_utimens(const char *path, const struct timespec ts[2])
-{
- struct hdfsConn *conn = NULL;
- hdfsFS fs;
- int ret = 0;
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
-
- TRACE1("utimens", path)
-
- assert(path);
- assert(dfs);
- assert('/' == *path);
-
- time_t aTime = ts[0].tv_sec;
- time_t mTime = ts[1].tv_sec;
-
- ret = fuseConnectAsThreadUid(&conn);
- if (ret) {
- fprintf(stderr, "fuseConnectAsThreadUid: failed to open a libhdfs "
- "connection! error %d.\n", ret);
- ret = -EIO;
- goto cleanup;
- }
- fs = hdfsConnGetFs(conn);
-
- if (hdfsUtime(fs, path, mTime, aTime)) {
- hdfsFileInfo *info = hdfsGetPathInfo(fs, path);
- if (info == NULL) {
- ret = (errno > 0) ? -errno : -ENOENT;
- goto cleanup;
- }
- // Silently ignore utimens failure for directories, otherwise
- // some programs like tar will fail.
- if (info->mKind == kObjectKindDirectory) {
- ret = 0;
- } else {
- ret = (errno > 0) ? -errno : -EACCES;
- }
- goto cleanup;
- }
- ret = 0;
-
-cleanup:
- if (conn) {
- hdfsConnRelease(conn);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_write.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_write.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_write.c
deleted file mode 100644
index 3090e9e..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_impls_write.c
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_connect.h"
-#include "fuse_dfs.h"
-#include "fuse_impls.h"
-#include "fuse_file_handle.h"
-
-int dfs_write(const char *path, const char *buf, size_t size,
- off_t offset, struct fuse_file_info *fi)
-{
- TRACE1("write", path)
-
- // retrieve dfs specific data
- dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
- int ret = 0;
-
- // check params and the context var
- assert(path);
- assert(dfs);
- assert('/' == *path);
- assert(fi);
-
- dfs_fh *fh = (dfs_fh*)fi->fh;
- assert(fh);
-
- hdfsFile file_handle = (hdfsFile)fh->hdfsFH;
- assert(file_handle);
-
- //
- // Critical section - make the sanity check (tell to see the writes are sequential) and the actual write
- // (no returns until end)
- //
- pthread_mutex_lock(&fh->mutex);
-
- tSize length = 0;
- hdfsFS fs = hdfsConnGetFs(fh->conn);
-
- tOffset cur_offset = hdfsTell(fs, file_handle);
- if (cur_offset != offset) {
- ERROR("User trying to random access write to a file %d != %d for %s",
- (int)cur_offset, (int)offset, path);
- ret = -ENOTSUP;
- } else {
- length = hdfsWrite(fs, file_handle, buf, size);
- if (length <= 0) {
- ERROR("Could not write all bytes for %s %d != %d (errno=%d)",
- path, length, (int)size, errno);
- if (errno == 0 || errno == EINTERNAL) {
- ret = -EIO;
- } else {
- ret = -errno;
- }
- }
- if (length != size) {
- ERROR("Could not write all bytes for %s %d != %d (errno=%d)",
- path, length, (int)size, errno);
- }
- }
-
- //
- // Critical section end
- //
-
- pthread_mutex_unlock(&fh->mutex);
-
- return ret == 0 ? length : ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_init.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_init.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_init.c
deleted file mode 100644
index 4da6da0..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_init.c
+++ /dev/null
@@ -1,192 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_dfs.h"
-#include "fuse_init.h"
-#include "fuse_options.h"
-#include "fuse_context_handle.h"
-#include "fuse_connect.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-static void print_env_vars(void)
-{
- const char *cp = getenv("CLASSPATH");
- const char *ld = getenv("LD_LIBRARY_PATH");
-
- ERROR("LD_LIBRARY_PATH=%s",ld == NULL ? "NULL" : ld);
- ERROR("CLASSPATH=%s",cp == NULL ? "NULL" : cp);
-}
-
-// Hacked up function to basically do:
-// protectedpaths = split(options.protected,':');
-
-static void init_protectedpaths(dfs_context *dfs)
-{
- char *tmp = options.protected;
-
- // handle degenerate case up front.
- if (tmp == NULL || 0 == *tmp) {
- dfs->protectedpaths = (char**)malloc(sizeof(char*));
- dfs->protectedpaths[0] = NULL;
- return;
- }
-
- if (options.debug) {
- print_options();
- }
-
- int i = 0;
- while (tmp && (NULL != (tmp = index(tmp,':')))) {
- tmp++; // pass the ,
- i++;
- }
- i++; // for the last entry
- i++; // for the final NULL
- dfs->protectedpaths = (char**)malloc(sizeof(char*)*i);
- assert(dfs->protectedpaths);
- tmp = options.protected;
- int j = 0;
- while (NULL != tmp && j < i) {
- int length;
- char *eos = index(tmp,':');
- if (NULL != eos) {
- length = eos - tmp; // length of this value
- } else {
- length = strlen(tmp);
- }
- dfs->protectedpaths[j] = (char*)malloc(sizeof(char)*length+1);
- assert(dfs->protectedpaths[j]);
- strncpy(dfs->protectedpaths[j], tmp, length);
- dfs->protectedpaths[j][length] = '\0';
- if (eos) {
- tmp = eos + 1;
- } else {
- tmp = NULL;
- }
- j++;
- }
- dfs->protectedpaths[j] = NULL;
-}
-
-static void dfsPrintOptions(FILE *fp, const struct options *o)
-{
- INFO("Mounting with options: [ protected=%s, nn_uri=%s, nn_port=%d, "
- "debug=%d, read_only=%d, initchecks=%d, "
- "no_permissions=%d, usetrash=%d, entry_timeout=%d, "
- "attribute_timeout=%d, rdbuffer_size=%zd, direct_io=%d ]",
- (o->protected ? o->protected : "(NULL)"), o->nn_uri, o->nn_port,
- o->debug, o->read_only, o->initchecks,
- o->no_permissions, o->usetrash, o->entry_timeout,
- o->attribute_timeout, o->rdbuffer_size, o->direct_io);
-}
-
-void *dfs_init(struct fuse_conn_info *conn)
-{
- int ret;
-
- //
- // Create a private struct of data we will pass to fuse here and which
- // will then be accessible on every call.
- //
- dfs_context *dfs = calloc(1, sizeof(*dfs));
- if (!dfs) {
- ERROR("FATAL: could not malloc dfs_context");
- exit(1);
- }
-
- // initialize the context
- dfs->debug = options.debug;
- dfs->usetrash = options.usetrash;
- dfs->protectedpaths = NULL;
- dfs->rdbuffer_size = options.rdbuffer_size;
- dfs->direct_io = options.direct_io;
-
- dfsPrintOptions(stderr, &options);
-
- init_protectedpaths(dfs);
- assert(dfs->protectedpaths != NULL);
-
- if (dfs->rdbuffer_size <= 0) {
- DEBUG("dfs->rdbuffersize <= 0 = %zd", dfs->rdbuffer_size);
- dfs->rdbuffer_size = 32768;
- }
-
- ret = fuseConnectInit(options.nn_uri, options.nn_port);
- if (ret) {
- ERROR("FATAL: dfs_init: fuseConnectInit failed with error %d!", ret);
- print_env_vars();
- exit(EXIT_FAILURE);
- }
- if (options.initchecks == 1) {
- ret = fuseConnectTest();
- if (ret) {
- ERROR("FATAL: dfs_init: fuseConnectTest failed with error %d!", ret);
- print_env_vars();
- exit(EXIT_FAILURE);
- }
- }
-
-#ifdef FUSE_CAP_ATOMIC_O_TRUNC
- // If FUSE_CAP_ATOMIC_O_TRUNC is set, open("foo", O_CREAT | O_TRUNC) will
- // result in dfs_open being called with O_TRUNC.
- //
- // If this capability is not present, fuse will try to use multiple
- // operation to "simulate" open(O_TRUNC). This doesn't work very well with
- // HDFS.
- // Unfortunately, this capability is only implemented on Linux 2.6.29 or so.
- // See HDFS-4140 for details.
- if (conn->capable & FUSE_CAP_ATOMIC_O_TRUNC) {
- conn->want |= FUSE_CAP_ATOMIC_O_TRUNC;
- }
-#endif
-
-#ifdef FUSE_CAP_ASYNC_READ
- // We're OK with doing reads at the same time as writes.
- if (conn->capable & FUSE_CAP_ASYNC_READ) {
- conn->want |= FUSE_CAP_ASYNC_READ;
- }
-#endif
-
-#ifdef FUSE_CAP_BIG_WRITES
- // Yes, we can read more than 4kb at a time. In fact, please do!
- if (conn->capable & FUSE_CAP_BIG_WRITES) {
- conn->want |= FUSE_CAP_BIG_WRITES;
- }
-#endif
-
-#ifdef FUSE_CAP_DONT_MASK
- if ((options.no_permissions) && (conn->capable & FUSE_CAP_DONT_MASK)) {
- // If we're handing permissions ourselves, we don't want the kernel
- // applying its own umask. HDFS already implements its own per-user
- // umasks! Sadly, this only actually does something on kernels 2.6.31 and
- // later.
- conn->want |= FUSE_CAP_DONT_MASK;
- }
-#endif
-
- return (void*)dfs;
-}
-
-
-void dfs_destroy(void *ptr)
-{
- TRACE("destroy")
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_init.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_init.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_init.h
deleted file mode 100644
index 681ab91..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_init.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_INIT_H__
-#define __FUSE_INIT_H__
-
-struct fuse_conn_info;
-
-/**
- * These are responsible for initializing connections to dfs and internal
- * data structures and then freeing them.
- * i.e., what happens on mount and unmount.
- *
- */
-void *dfs_init(struct fuse_conn_info *conn);
-void dfs_destroy (void *ptr);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_options.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_options.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_options.c
deleted file mode 100644
index 8461ce4..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_options.c
+++ /dev/null
@@ -1,188 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "fuse_context_handle.h"
-#include "fuse_dfs.h"
-#include "fuse_options.h"
-
-#include <getopt.h>
-#include <stdlib.h>
-
-#define OLD_HDFS_URI_LOCATION "dfs://"
-#define NEW_HDFS_URI_LOCATION "hdfs://"
-
-void print_options() {
- printf("options:\n"
- "\tprotected=%s\n"
- "\tserver=%s\n"
- "\tport=%d\n"
- "\tdebug=%d\n"
- "\tread_only=%d\n"
- "\tusetrash=%d\n"
- "\tentry_timeout=%d\n"
- "\tattribute_timeout=%d\n"
- "\tprivate=%d\n"
- "\trdbuffer_size=%d (KBs)\n",
- options.protected, options.nn_uri, options.nn_port, options.debug,
- options.read_only, options.usetrash, options.entry_timeout,
- options.attribute_timeout, options.private,
- (int)options.rdbuffer_size / 1024);
-}
-
-const char *program;
-
-/** macro to define options */
-#define DFSFS_OPT_KEY(t, p, v) { t, offsetof(struct options, p), v }
-
-void print_usage(const char *pname)
-{
- printf("USAGE: %s [debug] [--help] [--version] "
- "[-oprotected=<colon_seped_list_of_paths] [rw] [-onotrash] "
- "[-ousetrash] [-obig_writes] [-oprivate (single user)] [ro] "
- "[-oserver=<hadoop_servername>] [-oport=<hadoop_port>] "
- "[-oentry_timeout=<secs>] [-oattribute_timeout=<secs>] "
- "[-odirect_io] [-onopoermissions] [-o<other fuse option>] "
- "<mntpoint> [fuse options]\n", pname);
- printf("NOTE: debugging option for fuse is -debug\n");
-}
-
-
-/** keys for FUSE_OPT_ options */
-enum
- {
- KEY_VERSION,
- KEY_HELP,
- KEY_USETRASH,
- KEY_NOTRASH,
- KEY_RO,
- KEY_RW,
- KEY_PRIVATE,
- KEY_BIGWRITES,
- KEY_DEBUG,
- KEY_INITCHECKS,
- KEY_NOPERMISSIONS,
- KEY_DIRECTIO,
- };
-
-struct fuse_opt dfs_opts[] =
- {
- DFSFS_OPT_KEY("server=%s", nn_uri, 0),
- DFSFS_OPT_KEY("entry_timeout=%d", entry_timeout, 0),
- DFSFS_OPT_KEY("attribute_timeout=%d", attribute_timeout, 0),
- DFSFS_OPT_KEY("protected=%s", protected, 0),
- DFSFS_OPT_KEY("port=%d", nn_port, 0),
- DFSFS_OPT_KEY("rdbuffer=%d", rdbuffer_size,0),
-
- FUSE_OPT_KEY("private", KEY_PRIVATE),
- FUSE_OPT_KEY("ro", KEY_RO),
- FUSE_OPT_KEY("debug", KEY_DEBUG),
- FUSE_OPT_KEY("initchecks", KEY_INITCHECKS),
- FUSE_OPT_KEY("nopermissions", KEY_NOPERMISSIONS),
- FUSE_OPT_KEY("big_writes", KEY_BIGWRITES),
- FUSE_OPT_KEY("rw", KEY_RW),
- FUSE_OPT_KEY("usetrash", KEY_USETRASH),
- FUSE_OPT_KEY("notrash", KEY_NOTRASH),
- FUSE_OPT_KEY("direct_io", KEY_DIRECTIO),
- FUSE_OPT_KEY("-v", KEY_VERSION),
- FUSE_OPT_KEY("--version", KEY_VERSION),
- FUSE_OPT_KEY("-h", KEY_HELP),
- FUSE_OPT_KEY("--help", KEY_HELP),
- FUSE_OPT_END
- };
-
-int dfs_options(void *data, const char *arg, int key, struct fuse_args *outargs)
-{
- (void) data;
- int nn_uri_len;
-
- switch (key) {
- case FUSE_OPT_KEY_OPT:
- INFO("Ignoring option %s", arg);
- return 1;
- case KEY_VERSION:
- INFO("%s %s\n", program, _FUSE_DFS_VERSION);
- exit(0);
- case KEY_HELP:
- print_usage(program);
- exit(0);
- case KEY_USETRASH:
- options.usetrash = 1;
- break;
- case KEY_NOTRASH:
- options.usetrash = 0;
- break;
- case KEY_RO:
- options.read_only = 1;
- break;
- case KEY_RW:
- options.read_only = 0;
- break;
- case KEY_PRIVATE:
- options.private = 1;
- break;
- case KEY_DEBUG:
- fuse_opt_add_arg(outargs, "-d");
- options.debug = 1;
- break;
- case KEY_INITCHECKS:
- options.initchecks = 1;
- break;
- case KEY_NOPERMISSIONS:
- options.no_permissions = 1;
- break;
- case KEY_DIRECTIO:
- options.direct_io = 1;
- break;
- case KEY_BIGWRITES:
-#ifdef FUSE_CAP_BIG_WRITES
- fuse_opt_add_arg(outargs, "-obig_writes");
-#endif
- break;
- default: {
- // try and see if the arg is a URI
- if (!strstr(arg, "://")) {
- if (strcmp(arg,"ro") == 0) {
- options.read_only = 1;
- } else if (strcmp(arg,"rw") == 0) {
- options.read_only = 0;
- } else {
- INFO("Adding FUSE arg %s", arg);
- fuse_opt_add_arg(outargs, arg);
- return 0;
- }
- } else {
- if (options.nn_uri) {
- INFO("Ignoring option %s because '-server' was already "
- "specified!", arg);
- return 1;
- }
- if (strstr(arg, OLD_HDFS_URI_LOCATION) == arg) {
- // For historical reasons, we let people refer to hdfs:// as dfs://
- nn_uri_len = strlen(NEW_HDFS_URI_LOCATION) +
- strlen(arg + strlen(OLD_HDFS_URI_LOCATION)) + 1;
- options.nn_uri = malloc(nn_uri_len);
- snprintf(options.nn_uri, nn_uri_len, "%s%s", NEW_HDFS_URI_LOCATION,
- arg + strlen(OLD_HDFS_URI_LOCATION));
- } else {
- options.nn_uri = strdup(arg);
- }
- }
- }
- }
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_options.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_options.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_options.h
deleted file mode 100644
index 4bfc235..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_options.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_OPTIONS_H__
-#define __FUSE_OPTIONS_H__
-
-/** options for fuse_opt.h */
-struct options {
- char* protected;
- char* nn_uri;
- int nn_port;
- int debug;
- int read_only;
- int initchecks;
- int no_permissions;
- int usetrash;
- int entry_timeout;
- int attribute_timeout;
- int private;
- size_t rdbuffer_size;
- int direct_io;
-} options;
-
-extern struct fuse_opt dfs_opts[];
-void print_options();
-void print_usage(const char *pname);
-int dfs_options(void *data, const char *arg, int key, struct fuse_args *outargs);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.c
deleted file mode 100644
index e3a0725..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.c
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include <math.h>
-#include <pthread.h>
-#include <grp.h>
-#include <pwd.h>
-
-#include "fuse_dfs.h"
-#include "fuse_stat_struct.h"
-#include "fuse_context_handle.h"
-
-/*
- * getpwuid and getgrgid return static structs so we safeguard the contents
- * while retrieving fields using the 2 structs below.
- * NOTE: if using both, always get the passwd struct firt!
- */
-extern pthread_mutex_t passwdstruct_mutex;
-extern pthread_mutex_t groupstruct_mutex;
-
-const int default_id = 99; // nobody - not configurable since soon uids in dfs, yeah!
-const int blksize = 512;
-
-/**
- * Converts from a hdfs hdfsFileInfo to a POSIX stat struct
- *
- */
-int fill_stat_structure(hdfsFileInfo *info, struct stat *st)
-{
- assert(st);
- assert(info);
-
- // initialize the stat structure
- memset(st, 0, sizeof(struct stat));
-
- // by default: set to 0 to indicate not supported for directory because we cannot (efficiently) get this info for every subdirectory
- st->st_nlink = (info->mKind == kObjectKindDirectory) ? 0 : 1;
-
- uid_t owner_id = default_id;
- if (info->mOwner != NULL) {
- //
- // Critical section - protect from concurrent calls in different threads since
- // the struct below is static.
- // (no returns until end)
- //
- pthread_mutex_lock(&passwdstruct_mutex);
-
- struct passwd *passwd_info = getpwnam(info->mOwner);
- owner_id = passwd_info == NULL ? default_id : passwd_info->pw_uid;
-
- //
- // End critical section
- //
- pthread_mutex_unlock(&passwdstruct_mutex);
-
- }
-
- gid_t group_id = default_id;
-
- if (info->mGroup != NULL) {
- //
- // Critical section - protect from concurrent calls in different threads since
- // the struct below is static.
- // (no returns until end)
- //
- pthread_mutex_lock(&groupstruct_mutex);
-
- struct group *grp = getgrnam(info->mGroup);
- group_id = grp == NULL ? default_id : grp->gr_gid;
-
- //
- // End critical section
- //
- pthread_mutex_unlock(&groupstruct_mutex);
-
- }
-
- short perm = (info->mKind == kObjectKindDirectory) ? (S_IFDIR | 0777) : (S_IFREG | 0666);
- if (info->mPermissions > 0) {
- perm = (info->mKind == kObjectKindDirectory) ? S_IFDIR: S_IFREG ;
- perm |= info->mPermissions;
- }
-
- // set stat metadata
- st->st_size = (info->mKind == kObjectKindDirectory) ? 4096 : info->mSize;
- st->st_blksize = blksize;
- st->st_blocks = ceil(st->st_size/st->st_blksize);
- st->st_mode = perm;
- st->st_uid = owner_id;
- st->st_gid = group_id;
- st->st_atime = info->mLastAccess;
- st->st_mtime = info->mLastMod;
- st->st_ctime = info->mLastMod;
-
- return 0;
-}
-
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.h
deleted file mode 100644
index d42a371..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_STAT_STRUCT_H__
-#define __FUSE_STAT_STRUCT_H__
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include "hdfs.h"
-
-/**
- * Converts from a hdfs hdfsFileInfo to a POSIX stat struct
- * Should be thread safe.
- */
-int fill_stat_structure(hdfsFileInfo *info, struct stat *st) ;
-
-extern const int default_id;
-extern const int blksize;
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_trash.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_trash.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_trash.c
deleted file mode 100644
index 5e58087..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_trash.c
+++ /dev/null
@@ -1,244 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include <hdfs.h>
-#include <inttypes.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <strings.h>
-
-#include "fuse_context_handle.h"
-#include "fuse_dfs.h"
-#include "fuse_trash.h"
-#include "fuse_users.h"
-
-#define TRASH_RENAME_TRIES 100
-#define ALREADY_IN_TRASH_ERR 9000
-
-/**
- * Split a path into a parent directory and a base path component.
- *
- * @param abs_path The absolute path.
- * @param pcomp (out param) Will be set to the last path component.
- * Malloced.
- * @param parent_dir (out param) Will be set to the parent directory.
- * Malloced.
- *
- * @return 0 on success.
- * On success, both *pcomp and *parent_dir will contain
- * malloc'ed strings.
- * EINVAL if the path wasn't absolute.
- * EINVAL if there is no parent directory (i.e. abs_path=/)
- * ENOMEM if we ran out of memory.
- */
-static int get_parent_dir(const char *abs_path, char **pcomp,
- char **parent_dir)
-{
- int ret;
- char *pdir = NULL, *pc = NULL, *last_slash;
-
- pdir = strdup(abs_path);
- if (!pdir) {
- ret = ENOMEM;
- goto done;
- }
- last_slash = rindex(pdir, '/');
- if (!last_slash) {
- ERROR("get_parent_dir(%s): expected absolute path.\n", abs_path);
- ret = EINVAL;
- goto done;
- }
- if (last_slash[1] == '\0') {
- *last_slash = '\0';
- last_slash = rindex(pdir, '/');
- if (!last_slash) {
- ERROR("get_parent_dir(%s): there is no parent dir.\n", abs_path);
- ret = EINVAL;
- goto done;
- }
- }
- pc = strdup(last_slash + 1);
- if (!pc) {
- ret = ENOMEM;
- goto done;
- }
- *last_slash = '\0';
- ret = 0;
-done:
- if (ret) {
- free(pdir);
- free(pc);
- return ret;
- }
- *pcomp = pc;
- *parent_dir = pdir;
- return 0;
-}
-
-/**
- * Get the base path to the trash. This will depend on the user ID.
- * For example, a user whose ID maps to 'foo' will get back the path
- * "/user/foo/.Trash/Current".
- *
- * @param trash_base (out param) the base path to the trash.
- * Malloced.
- *
- * @return 0 on success; error code otherwise.
- */
-static int get_trash_base(char **trash_base)
-{
- const char * const PREFIX = "/user/";
- const char * const SUFFIX = "/.Trash/Current";
- char *user_name = NULL, *base = NULL;
- uid_t uid = fuse_get_context()->uid;
- int ret;
-
- user_name = getUsername(uid);
- if (!user_name) {
- ERROR("get_trash_base(): failed to get username for uid %"PRId64"\n",
- (uint64_t)uid);
- ret = EIO;
- goto done;
- }
- if (asprintf(&base, "%s%s%s", PREFIX, user_name, SUFFIX) < 0) {
- base = NULL;
- ret = ENOMEM;
- goto done;
- }
- ret = 0;
-done:
- free(user_name);
- if (ret) {
- free(base);
- return ret;
- }
- *trash_base = base;
- return 0;
-}
-
-//
-// NOTE: this function is a c implementation of org.apache.hadoop.fs.Trash.moveToTrash(Path path).
-//
-int move_to_trash(const char *abs_path, hdfsFS userFS)
-{
- int ret;
- char *pcomp = NULL, *parent_dir = NULL, *trash_base = NULL;
- char *target_dir = NULL, *target = NULL;
-
- ret = get_parent_dir(abs_path, &pcomp, &parent_dir);
- if (ret) {
- goto done;
- }
- ret = get_trash_base(&trash_base);
- if (ret) {
- goto done;
- }
- int trash_base_len = strlen(trash_base);
- if (!strncmp(trash_base, abs_path, trash_base_len)
- && (strlen(abs_path) == trash_base_len || abs_path[trash_base_len] == '/')) {
- INFO("move_to_trash(%s): file is already in the trash; deleting.",
- abs_path);
- ret = ALREADY_IN_TRASH_ERR;
- goto done;
- }
- if (asprintf(&target_dir, "%s%s", trash_base, parent_dir) < 0) {
- ret = ENOMEM;
- target_dir = NULL;
- goto done;
- }
- if (asprintf(&target, "%s/%s", target_dir, pcomp) < 0) {
- ret = ENOMEM;
- target = NULL;
- goto done;
- }
- // create the target trash directory in trash (if needed)
- if (hdfsExists(userFS, target_dir) != 0) {
- // make the directory to put it in in the Trash - NOTE
- // hdfsCreateDirectory also creates parents, so Current will be created if it does not exist.
- if (hdfsCreateDirectory(userFS, target_dir)) {
- ret = errno;
- ERROR("move_to_trash(%s) error: hdfsCreateDirectory(%s) failed with error %d",
- abs_path, target_dir, ret);
- goto done;
- }
- } else if (hdfsExists(userFS, target) == 0) {
- // If there is already a file in the trash with this path, append a number.
- int idx;
- for (idx = 1; idx < TRASH_RENAME_TRIES; idx++) {
- free(target);
- if (asprintf(&target, "%s/%s.%d", target_dir, pcomp, idx) < 0) {
- target = NULL;
- ret = ENOMEM;
- goto done;
- }
- if (hdfsExists(userFS, target) != 0) {
- break;
- }
- }
- if (idx == TRASH_RENAME_TRIES) {
- ERROR("move_to_trash(%s) error: there are already %d files in the trash "
- "with this name.\n", abs_path, TRASH_RENAME_TRIES);
- ret = EINVAL;
- goto done;
- }
- }
- if (hdfsRename(userFS, abs_path, target)) {
- ret = errno;
- ERROR("move_to_trash(%s): failed to rename the file to %s: error %d",
- abs_path, target, ret);
- goto done;
- }
-
- ret = 0;
-done:
- if ((ret != 0) && (ret != ALREADY_IN_TRASH_ERR)) {
- ERROR("move_to_trash(%s) failed with error %d", abs_path, ret);
- }
- free(pcomp);
- free(parent_dir);
- free(trash_base);
- free(target_dir);
- free(target);
- return ret;
-}
-
-int hdfsDeleteWithTrash(hdfsFS userFS, const char *path, int useTrash)
-{
- int tried_to_move_to_trash = 0;
- if (useTrash) {
- tried_to_move_to_trash = 1;
- if (move_to_trash(path, userFS) == 0) {
- return 0;
- }
- }
- if (hdfsDelete(userFS, path, 1)) {
- int err = errno;
- if (err < 0) {
- err = -err;
- }
- ERROR("hdfsDeleteWithTrash(%s): hdfsDelete failed: error %d.",
- path, err);
- return -err;
- }
- if (tried_to_move_to_trash) {
- ERROR("hdfsDeleteWithTrash(%s): deleted the file instead.\n", path);
- }
- return 0;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_trash.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_trash.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_trash.h
deleted file mode 100644
index 220ce3d..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_trash.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_TRASH_H__
-#define __FUSE_TRASH_H__
-
-#include <hdfs.h>
-
-int hdfsDeleteWithTrash(hdfsFS userFS, const char *path, int useTrash);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_users.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_users.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_users.c
deleted file mode 100644
index d7bdfe7..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_users.c
+++ /dev/null
@@ -1,213 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-
-#include <pthread.h>
-#include <grp.h>
-#include <pwd.h>
-#include <stdlib.h>
-
-#include "fuse_dfs.h"
-
-/*
- * getpwuid and getgrgid return static structs so we safeguard the contents
- * while retrieving fields using the 2 structs below.
- * NOTE: if using both, always get the passwd struct firt!
- */
-pthread_mutex_t passwdstruct_mutex = PTHREAD_MUTEX_INITIALIZER;
-pthread_mutex_t groupstruct_mutex = PTHREAD_MUTEX_INITIALIZER;
-
-/*
- * Utility for getting the user making the fuse call in char * form
- * NOTE: if non-null return, the return must be freed by the caller.
- */
-char *getUsername(uid_t uid) {
- //
- // Critical section - protect from concurrent calls in different threads.
- // since the struct below is static.
- // (no returns until end)
- //
-
- pthread_mutex_lock(&passwdstruct_mutex);
-
- struct passwd *userinfo = getpwuid(uid);
- char * ret = userinfo && userinfo->pw_name ? strdup(userinfo->pw_name) : NULL;
-
- pthread_mutex_unlock(&passwdstruct_mutex);
-
- //
- // End critical section
- //
- return ret;
-}
-
-/**
- * Cleans up a char ** group pointer
- */
-
-void freeGroups(char **groups, int numgroups) {
- if (groups == NULL) {
- return;
- }
- int i ;
- for (i = 0; i < numgroups; i++) {
- free(groups[i]);
- }
- free(groups);
-}
-
-#define GROUPBUF_SIZE 5
-
-char *getGroup(gid_t gid) {
- //
- // Critical section - protect from concurrent calls in different threads.
- // since the struct below is static.
- // (no returns until end)
- //
-
- pthread_mutex_lock(&groupstruct_mutex);
-
- struct group* grp = getgrgid(gid);
- char * ret = grp && grp->gr_name ? strdup(grp->gr_name) : NULL;
-
- //
- // End critical section
- //
- pthread_mutex_unlock(&groupstruct_mutex);
-
- return ret;
-}
-
-
-/**
- * Utility for getting the group from the uid
- * NOTE: if non-null return, the return must be freed by the caller.
- */
-char *getGroupUid(uid_t uid) {
- //
- // Critical section - protect from concurrent calls in different threads
- // since the structs below are static.
- // (no returns until end)
- //
-
- pthread_mutex_lock(&passwdstruct_mutex);
- pthread_mutex_lock(&groupstruct_mutex);
-
- char *ret = NULL;
- struct passwd *userinfo = getpwuid(uid);
- if (NULL != userinfo) {
- struct group* grp = getgrgid( userinfo->pw_gid);
- ret = grp && grp->gr_name ? strdup(grp->gr_name) : NULL;
- }
-
- //
- // End critical section
- //
- pthread_mutex_unlock(&groupstruct_mutex);
- pthread_mutex_unlock(&passwdstruct_mutex);
-
- return ret;
-}
-
-
-/**
- * lookup the gid based on the uid
- */
-gid_t getGidUid(uid_t uid) {
- //
- // Critical section - protect from concurrent calls in different threads
- // since the struct below is static.
- // (no returns until end)
- //
-
- pthread_mutex_lock(&passwdstruct_mutex);
-
- struct passwd *userinfo = getpwuid(uid);
- gid_t gid = userinfo == NULL ? 0 : userinfo->pw_gid;
-
- //
- // End critical section
- //
- pthread_mutex_unlock(&passwdstruct_mutex);
-
- return gid;
-}
-
-/**
- * Utility for getting the groups for the user making the fuse call in char * form
- */
-char ** getGroups(uid_t uid, int *num_groups)
-{
- char *user = getUsername(uid);
-
- if (user == NULL)
- return NULL;
-
- char **groupnames = NULL;
-
- // see http://www.openldap.org/lists/openldap-devel/199903/msg00023.html
-
- //#define GETGROUPS_T 1
-#ifdef GETGROUPS_T
- *num_groups = GROUPBUF_SIZE;
-
- gid_t* grouplist = malloc(GROUPBUF_SIZE * sizeof(gid_t));
- assert(grouplist != NULL);
- gid_t* tmp_grouplist;
- int rtr;
-
- gid_t gid = getGidUid(uid);
-
- if ((rtr = getgrouplist(user, gid, grouplist, num_groups)) == -1) {
- // the buffer we passed in is < *num_groups
- if ((tmp_grouplist = realloc(grouplist, *num_groups * sizeof(gid_t))) != NULL) {
- grouplist = tmp_grouplist;
- getgrouplist(user, gid, grouplist, num_groups);
- }
- }
-
- groupnames = (char**)malloc(sizeof(char*)* (*num_groups) + 1);
- assert(groupnames);
- int i;
- for (i=0; i < *num_groups; i++) {
- groupnames[i] = getGroup(grouplist[i]);
- if (groupnames[i] == NULL) {
- ERROR("Could not lookup group %d\n", (int)grouplist[i]);
- }
- }
- free(grouplist);
- assert(user != NULL);
- groupnames[i] = user;
- *num_groups = *num_groups + 1;
-#else
-
- int i = 0;
- assert(user != NULL);
- groupnames[i] = user;
- i++;
-
- groupnames[i] = getGroupUid(uid);
- if (groupnames[i]) {
- i++;
- }
-
- *num_groups = i;
-
-#endif
- return groupnames;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_users.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_users.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_users.h
deleted file mode 100644
index d63d916..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_users.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_USERS_H__
-#define __FUSE_USERS_H__
-
-#include <grp.h>
-#include <pwd.h>
-#include <pthread.h>
-
-/**
- * Overall Note:
- * 1. all these functions should be thread safe.
- * 2. the ones that return char * or char **, generally require
- * the caller to free the return value.
- *
- */
-
-
-/**
- * Utility for getting the user making the fuse call in char * form
- * NOTE: if non-null return, the return must be freed by the caller.
- */
-char *getUsername(uid_t uid);
-
-
-/**
- * Cleans up a char ** group pointer
- */
-void freeGroups(char **groups, int numgroups);
-
-/**
- * Lookup single group. Caller responsible for free of the return value
- */
-char *getGroup(gid_t gid);
-
-/**
- * Utility for getting the group from the uid
- * NOTE: if non-null return, the return must be freed by the caller.
- */
-char *getGroupUid(uid_t uid) ;
-
-
-/**
- * lookup the gid based on the uid
- */
-
-gid_t getGidUid(uid_t uid);
-
-/**
- * Utility for getting the groups for the user making the fuse call in char * form
- */
-char ** getGroups(uid_t uid, int *num_groups);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/TestFuseDFS.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/TestFuseDFS.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/TestFuseDFS.java
deleted file mode 100644
index a5d9abd..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/TestFuseDFS.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import java.io.*;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.concurrent.atomic.*;
-
-import org.apache.log4j.Level;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.*;
-import org.apache.hadoop.fs.permission.*;
-import org.apache.hadoop.hdfs.*;
-import org.apache.hadoop.io.IOUtils;
-import org.apache.hadoop.test.GenericTestUtils;
-import org.apache.hadoop.util.StringUtils;
-
-import org.junit.Test;
-import org.junit.BeforeClass;
-import org.junit.AfterClass;
-import static org.junit.Assert.*;
-
-/**
- * Basic functional tests on a fuse-dfs mount.
- */
-public class TestFuseDFS {
-
- private static MiniDFSCluster cluster;
- private static FileSystem fs;
- private static Process fuseProcess;
- private static Runtime r;
- private static String mountPoint;
-
- private static final Log LOG = LogFactory.getLog(TestFuseDFS.class);
- {
- GenericTestUtils.setLogLevel(LOG, Level.ALL);
- }
-
- /** Dump the given intput stream to stderr */
- private static void dumpInputStream(InputStream is) throws IOException {
- int len;
- do {
- byte b[] = new byte[is.available()];
- len = is.read(b);
- System.out.println("Read "+len+" bytes");
- System.out.write(b, 0, b.length);
- } while (len > 0);
- }
-
- /**
- * Wait for the given process to return and check that it exited
- * as required. Log if the process failed.
- */
- private static void checkProcessRet(Process p, boolean expectPass)
- throws IOException {
- try {
- int ret = p.waitFor();
- if (ret != 0) {
- dumpInputStream(p.getErrorStream());
- }
- if (expectPass) {
- assertEquals(0, ret);
- } else {
- assertTrue(ret != 0);
- }
- } catch (InterruptedException ie) {
- fail("Process interrupted: "+ie.getMessage());
- }
- }
-
- /** Exec the given command and assert it executed successfully */
- private static void execWaitRet(String cmd) throws IOException {
- LOG.debug("EXEC "+cmd);
- Process p = r.exec(cmd);
- try {
- p.waitFor();
- } catch (InterruptedException ie) {
- fail("Process interrupted: "+ie.getMessage());
- }
- }
-
- /** Exec the given command and assert it executed successfully */
- private static void execIgnoreRet(String cmd) throws IOException {
- LOG.debug("EXEC "+cmd);
- r.exec(cmd);
- }
-
- /** Exec the given command and assert it executed successfully */
- private static void execAssertSucceeds(String cmd) throws IOException {
- LOG.debug("EXEC "+cmd);
- checkProcessRet(r.exec(cmd), true);
- }
-
- /** Exec the given command, assert it returned an error code */
- private static void execAssertFails(String cmd) throws IOException {
- LOG.debug("EXEC "+cmd);
- checkProcessRet(r.exec(cmd), false);
- }
-
- /** Create and write the given file */
- private static void createFile(File f, String s) throws IOException {
- InputStream is = new ByteArrayInputStream(s.getBytes());
- FileOutputStream fos = new FileOutputStream(f);
- IOUtils.copyBytes(is, fos, s.length(), true);
- }
-
- /** Check that the given file exists with the given contents */
- private static void checkFile(File f, String expectedContents)
- throws IOException {
- FileInputStream fi = new FileInputStream(f);
- int len = expectedContents.length();
- byte[] b = new byte[len];
- try {
- IOUtils.readFully(fi, b, 0, len);
- } catch (IOException ie) {
- fail("Reading "+f.getName()+" failed with "+ie.getMessage());
- } finally {
- fi.close(); // NB: leaving f unclosed prevents unmount
- }
- String s = new String(b, 0, len);
- assertEquals("File content differs", expectedContents, s);
- }
-
- private static class RedirectToStdoutThread extends Thread {
- private InputStream is;
-
- RedirectToStdoutThread(InputStream is) {
- this.is = is;
- }
- public void run() {
- try {
- InputStreamReader isr = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isr);
- String line=null;
- while ( (line = br.readLine()) != null) {
- LOG.error("FUSE_LINE:" + line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- /** Run a fuse-dfs process to mount the given DFS */
- private static Process establishMount(URI uri) throws IOException {
- Runtime r = Runtime.getRuntime();
- String cp = System.getProperty("java.class.path");
-
- String buildTestDir = System.getProperty("build.test");
- String fuseCmd = buildTestDir + "/../fuse_dfs";
- String libHdfs = buildTestDir + "/../../../c++/lib";
-
- String arch = System.getProperty("os.arch");
- String jvm = System.getProperty("java.home") + "/lib/" + arch + "/server";
- String lp = System.getProperty("LD_LIBRARY_PATH")+":"+libHdfs+":"+jvm;
- LOG.debug("LD_LIBRARY_PATH=" + lp);
-
- String nameNode =
- "dfs://" + uri.getHost() + ":" + String.valueOf(uri.getPort());
-
- // NB: We're mounting via an unprivileged user, therefore
- // user_allow_other needs to be set in /etc/fuse.conf, which also
- // needs to be world readable.
- String mountCmd[] = {
- fuseCmd, nameNode, mountPoint,
- // "-odebug", // Don't daemonize
- "-obig_writes", // Allow >4kb writes
- "-oentry_timeout=0.1", // Don't cache dents long
- "-oattribute_timeout=0.1", // Don't cache attributes long
- "-ononempty", // Don't complain about junk in mount point
- "-f", // Don't background the process
- "-ordbuffer=32768", // Read buffer size in kb
- "rw"
- };
-
- String [] env = {
- "CLASSPATH="+cp,
- "LD_LIBRARY_PATH="+lp,
- "PATH=/usr/bin:/bin"
- };
-
- execWaitRet("fusermount -u " + mountPoint);
- execAssertSucceeds("rm -rf " + mountPoint);
- execAssertSucceeds("mkdir -p " + mountPoint);
-
- // Mount the mini cluster
- String cmdStr = "";
- for (String c : mountCmd) {
- cmdStr += (" " + c);
- }
- LOG.info("now mounting with:" + cmdStr);
- Process fuseProcess = r.exec(mountCmd, env);
- RedirectToStdoutThread stdoutThread =
- new RedirectToStdoutThread(fuseProcess.getInputStream());
- RedirectToStdoutThread stderrThread =
- new RedirectToStdoutThread(fuseProcess.getErrorStream());
- stdoutThread.start();
- stderrThread.start();
- // Wait for fusermount to start up, so that we know we're operating on the
- // FUSE FS when we run the tests.
- try {
- Thread.sleep(50000);
- } catch (InterruptedException e) {
- }
- return fuseProcess;
- }
-
- /** Tear down the fuse-dfs process and mount */
- private static void teardownMount() throws IOException {
- execWaitRet("fusermount -u " + mountPoint);
- try {
- assertEquals(0, fuseProcess.waitFor()); // fuse_dfs should exit cleanly
- } catch (InterruptedException e) {
- fail("interrupted while waiting for fuse_dfs process to exit.");
- }
- }
-
- @BeforeClass
- public static void startUp() throws IOException {
- Configuration conf = new HdfsConfiguration();
- r = Runtime.getRuntime();
- mountPoint = System.getProperty("build.test") + "/mnt";
- conf.setBoolean(DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY, false);
- cluster = new MiniDFSCluster.Builder(conf).build();
- cluster.waitClusterUp();
- fs = cluster.getFileSystem();
- fuseProcess = establishMount(fs.getUri());
- }
-
- @AfterClass
- public static void tearDown() throws IOException {
- // Unmount before taking down the mini cluster
- // so no outstanding operations hang.
- teardownMount();
- if (fs != null) {
- fs.close();
- }
- if (cluster != null) {
- cluster.shutdown();
- }
- }
-
- /** Test basic directory creation, access, removal */
- @Test
- public void testBasicDir() throws IOException {
- File d = new File(mountPoint, "dir1");
-
- // Mkdir, access and rm via the mount
- execAssertSucceeds("mkdir " + d.getAbsolutePath());
- execAssertSucceeds("ls " + d.getAbsolutePath());
- execAssertSucceeds("rmdir " + d.getAbsolutePath());
-
- // The dir should no longer exist
- execAssertFails("ls " + d.getAbsolutePath());
- }
-
- /** Test basic file creation and writing */
- @Test
- public void testCreate() throws IOException {
- final String contents = "hello world";
- File f = new File(mountPoint, "file1");
-
- // Create and access via the mount
- createFile(f, contents);
-
- // XX avoids premature EOF
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ie) { }
-
- checkFile(f, contents);
-
- // Cat, stat and delete via the mount
- execAssertSucceeds("cat " + f.getAbsolutePath());
- execAssertSucceeds("stat " + f.getAbsolutePath());
- execAssertSucceeds("rm " + f.getAbsolutePath());
-
- // The file should no longer exist
- execAssertFails("ls " + f.getAbsolutePath());
- }
-
- /** Test creating a file via touch */
- @Test
- public void testTouch() throws IOException {
- File f = new File(mountPoint, "file1");
- execAssertSucceeds("touch " + f.getAbsolutePath());
- execAssertSucceeds("rm " + f.getAbsolutePath());
- }
-
- /** Test random access to a file */
- @Test
- public void testRandomAccess() throws IOException {
- final String contents = "hello world";
- File f = new File(mountPoint, "file1");
-
- createFile(f, contents);
-
- RandomAccessFile raf = new RandomAccessFile(f, "rw");
- raf.seek(f.length());
- try {
- raf.write('b');
- } catch (IOException e) {
- // Expected: fuse-dfs not yet support append
- assertEquals("Operation not supported", e.getMessage());
- } finally {
- raf.close();
- }
-
- raf = new RandomAccessFile(f, "rw");
- raf.seek(0);
- try {
- raf.write('b');
- fail("Over-wrote existing bytes");
- } catch (IOException e) {
- // Expected: can-not overwrite a file
- assertEquals("Invalid argument", e.getMessage());
- } finally {
- raf.close();
- }
- execAssertSucceeds("rm " + f.getAbsolutePath());
- }
-
- /** Test copying a set of files from the mount to itself */
- @Test
- public void testCopyFiles() throws IOException {
- final String contents = "hello world";
- File d1 = new File(mountPoint, "dir1");
- File d2 = new File(mountPoint, "dir2");
-
- // Create and populate dir1 via the mount
- execAssertSucceeds("mkdir " + d1.getAbsolutePath());
- for (int i = 0; i < 5; i++) {
- createFile(new File(d1, "file"+i), contents);
- }
- assertEquals(5, d1.listFiles().length);
-
- // Copy dir from the mount to the mount
- execAssertSucceeds("cp -r " + d1.getAbsolutePath() +
- " " + d2.getAbsolutePath());
- assertEquals(5, d2.listFiles().length);
-
- // Access all the files in the dirs and remove them
- execAssertSucceeds("find " + d1.getAbsolutePath());
- execAssertSucceeds("find " + d2.getAbsolutePath());
- execAssertSucceeds("rm -r " + d1.getAbsolutePath());
- execAssertSucceeds("rm -r " + d2.getAbsolutePath());
- }
-
- /** Test concurrent creation and access of the mount */
- @Test
- public void testMultipleThreads() throws IOException {
- ArrayList<Thread> threads = new ArrayList<Thread>();
- final AtomicReference<String> errorMessage = new AtomicReference<String>();
-
- for (int i = 0; i < 10; i++) {
- Thread t = new Thread() {
- public void run() {
- try {
- File d = new File(mountPoint, "dir"+getId());
- execWaitRet("mkdir " + d.getAbsolutePath());
- for (int j = 0; j < 10; j++) {
- File f = new File(d, "file"+j);
- final String contents = "thread "+getId()+" "+j;
- createFile(f, contents);
- }
- for (int j = 0; j < 10; j++) {
- File f = new File(d, "file"+j);
- execWaitRet("cat " + f.getAbsolutePath());
- execWaitRet("rm " + f.getAbsolutePath());
- }
- execWaitRet("rmdir " + d.getAbsolutePath());
- } catch (IOException ie) {
- errorMessage.set(
- String.format("Exception %s",
- StringUtils.stringifyException(ie)));
- }
- }
- };
- t.start();
- threads.add(t);
- }
-
- for (Thread t : threads) {
- try {
- t.join();
- } catch (InterruptedException ie) {
- fail("Thread interrupted: "+ie.getMessage());
- }
- }
-
- assertNull(errorMessage.get(), errorMessage.get());
- }
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/fuse_workload.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/fuse_workload.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/fuse_workload.c
deleted file mode 100644
index 78fdbc6..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/fuse_workload.c
+++ /dev/null
@@ -1,403 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#define FUSE_USE_VERSION 26
-
-#include "fuse-dfs/test/fuse_workload.h"
-#include "libhdfs/expect.h"
-#include "util/posix_util.h"
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <fuse.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/statvfs.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <utime.h>
-
-typedef int (*testReadDirFn)(const struct dirent *de, void *v);
-
-struct fileCtx {
- int fd;
- char *str;
- int strLen;
- char *path;
-};
-
-static const char *DIRS_A_AND_B[] = { "a", "b", NULL };
-static const char *DIRS_B_AND_C[] = { "b", "c", NULL };
-
-#define LONG_STR_LEN 1024
-#define NUM_FILE_CTX 3
-#define MAX_TRIES 120
-
-// TODO: implement/test access, mknod, symlink
-// TODO: rmdir on non-dir, non-empty dir
-// TODO: test unlink-during-writing
-// TODO: test weird open flags failing
-// TODO: test chown, chmod
-
-static int testReadDirImpl(DIR *dp, testReadDirFn fn, void *data)
-{
- struct dirent *de;
- int ret, noda = 0;
-
- while (1) {
- de = readdir(dp);
- if (!de)
- return noda;
- if (!strcmp(de->d_name, "."))
- continue;
- if (!strcmp(de->d_name, ".."))
- continue;
- ret = fn(de, data);
- if (ret < 0)
- return ret;
- ++noda;
- }
- return noda;
-}
-
-static int testReadDir(const char *dirName, testReadDirFn fn, void *data)
-{
- int ret;
- DIR *dp;
-
- dp = opendir(dirName);
- if (!dp) {
- return -errno;
- }
- ret = testReadDirImpl(dp, fn, data);
- closedir(dp);
- return ret;
-}
-
-static int expectDirs(const struct dirent *de, void *v)
-{
- const char **names = v;
- const char **n;
-
- for (n = names; *n; ++n) {
- if (!strcmp(de->d_name, *n)) {
- return 0;
- }
- }
- return -ENOENT;
-}
-
-static int safeWrite(int fd, const void *buf, size_t amt)
-{
- while (amt > 0) {
- int r = write(fd, buf, amt);
- if (r < 0) {
- if (errno != EINTR)
- return -errno;
- continue;
- }
- amt -= r;
- buf = (const char *)buf + r;
- }
- return 0;
-}
-
-static int safeRead(int fd, void *buf, int c)
-{
- int res;
- size_t amt = 0;
-
- while (amt < c) {
- res = read(fd, buf, c - amt);
- if (res <= 0) {
- if (res == 0)
- return amt;
- if (errno != EINTR)
- return -errno;
- continue;
- }
- amt += res;
- buf = (char *)buf + res;
- }
- return amt;
-}
-
-/* Bug: HDFS-2551.
- * When a program writes a file, closes it, and immediately re-opens it,
- * it might not appear to have the correct length. This is because FUSE
- * invokes the release() callback asynchronously.
- *
- * To work around this, we keep retrying until the file length is what we
- * expect.
- */
-static int closeWorkaroundHdfs2551(int fd, const char *path, off_t expectedSize)
-{
- int ret, try;
- struct stat stBuf;
-
- RETRY_ON_EINTR_GET_ERRNO(ret, close(fd));
- EXPECT_ZERO(ret);
- for (try = 0; try < MAX_TRIES; try++) {
- EXPECT_ZERO(stat(path, &stBuf));
- EXPECT_NONZERO(S_ISREG(stBuf.st_mode));
- if (stBuf.st_size == expectedSize) {
- return 0;
- }
- sleepNoSig(1);
- }
- fprintf(stderr, "FUSE_WORKLOAD: error: expected file %s to have length "
- "%lld; instead, it had length %lld\n",
- path, (long long)expectedSize, (long long)stBuf.st_size);
- return -EIO;
-}
-
-#ifdef FUSE_CAP_ATOMIC_O_TRUNC
-
-/**
- * Test that we can create a file, write some contents to it, close that file,
- * and then successfully re-open with O_TRUNC.
- */
-static int testOpenTrunc(const char *base)
-{
- int fd, err;
- char path[PATH_MAX];
- const char * const SAMPLE1 = "this is the first file that we wrote.";
- const char * const SAMPLE2 = "this is the second file that we wrote. "
- "It's #2!";
-
- snprintf(path, sizeof(path), "%s/trunc.txt", base);
- fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0644);
- if (fd < 0) {
- err = errno;
- fprintf(stderr, "TEST_ERROR: testOpenTrunc(%s): first open "
- "failed with error %d\n", path, err);
- return -err;
- }
- EXPECT_ZERO(safeWrite(fd, SAMPLE1, strlen(SAMPLE1)));
- EXPECT_ZERO(closeWorkaroundHdfs2551(fd, path, strlen(SAMPLE1)));
- fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0644);
- if (fd < 0) {
- err = errno;
- fprintf(stderr, "TEST_ERROR: testOpenTrunc(%s): second open "
- "failed with error %d\n", path, err);
- return -err;
- }
- EXPECT_ZERO(safeWrite(fd, SAMPLE2, strlen(SAMPLE2)));
- EXPECT_ZERO(closeWorkaroundHdfs2551(fd, path, strlen(SAMPLE2)));
- return 0;
-}
-
-#else
-
-static int testOpenTrunc(const char *base)
-{
- fprintf(stderr, "FUSE_WORKLOAD: We lack FUSE_CAP_ATOMIC_O_TRUNC support. "
- "Not testing open(O_TRUNC).\n");
- return 0;
-}
-
-#endif
-
-int runFuseWorkloadImpl(const char *root, const char *pcomp,
- struct fileCtx *ctx)
-{
- char base[PATH_MAX], tmp[PATH_MAX], *tmpBuf;
- char src[PATH_MAX], dst[PATH_MAX];
- struct stat stBuf;
- int ret, i;
- struct utimbuf tbuf;
- struct statvfs stvBuf;
-
- // The root must be a directory
- EXPECT_ZERO(stat(root, &stBuf));
- EXPECT_NONZERO(S_ISDIR(stBuf.st_mode));
-
- // base = <root>/<pcomp>. base must not exist yet
- snprintf(base, sizeof(base), "%s/%s", root, pcomp);
- EXPECT_NEGATIVE_ONE_WITH_ERRNO(stat(base, &stBuf), ENOENT);
-
- // mkdir <base>
- RETRY_ON_EINTR_GET_ERRNO(ret, mkdir(base, 0755));
- EXPECT_ZERO(ret);
-
- // rmdir <base>
- RETRY_ON_EINTR_GET_ERRNO(ret, rmdir(base));
- EXPECT_ZERO(ret);
-
- // mkdir <base>
- RETRY_ON_EINTR_GET_ERRNO(ret, mkdir(base, 0755));
- EXPECT_ZERO(ret);
-
- // stat <base>
- EXPECT_ZERO(stat(base, &stBuf));
- EXPECT_NONZERO(S_ISDIR(stBuf.st_mode));
-
- // mkdir <base>/a
- snprintf(tmp, sizeof(tmp), "%s/a", base);
- RETRY_ON_EINTR_GET_ERRNO(ret, mkdir(tmp, 0755));
- EXPECT_ZERO(ret);
-
- /* readdir test */
- EXPECT_INT_EQ(1, testReadDir(base, expectDirs, DIRS_A_AND_B));
-
- // mkdir <base>/b
- snprintf(tmp, sizeof(tmp), "%s/b", base);
- RETRY_ON_EINTR_GET_ERRNO(ret, mkdir(tmp, 0755));
- EXPECT_ZERO(ret);
-
- // readdir a and b
- EXPECT_INT_EQ(2, testReadDir(base, expectDirs, DIRS_A_AND_B));
-
- // rename a -> c
- snprintf(src, sizeof(src), "%s/a", base);
- snprintf(dst, sizeof(dst), "%s/c", base);
- EXPECT_ZERO(rename(src, dst));
-
- // readdir c and b
- EXPECT_INT_EQ(-ENOENT, testReadDir(base, expectDirs, DIRS_A_AND_B));
- EXPECT_INT_EQ(2, testReadDir(base, expectDirs, DIRS_B_AND_C));
-
- // statvfs
- memset(&stvBuf, 0, sizeof(stvBuf));
- EXPECT_ZERO(statvfs(root, &stvBuf));
-
- // set utime on base
- memset(&tbuf, 0, sizeof(tbuf));
- tbuf.actime = 123;
- tbuf.modtime = 456;
- EXPECT_ZERO(utime(base, &tbuf));
-
- // stat(base)
- EXPECT_ZERO(stat(base, &stBuf));
- EXPECT_NONZERO(S_ISDIR(stBuf.st_mode));
- //EXPECT_INT_EQ(456, stBuf.st_atime); // hdfs doesn't store atime on directories
- EXPECT_INT_EQ(456, stBuf.st_mtime);
-
- // open some files and write to them
- for (i = 0; i < NUM_FILE_CTX; i++) {
- snprintf(tmp, sizeof(tmp), "%s/b/%d", base, i);
- ctx[i].path = strdup(tmp);
- if (!ctx[i].path) {
- fprintf(stderr, "FUSE_WORKLOAD: OOM on line %d\n", __LINE__);
- return -ENOMEM;
- }
- ctx[i].strLen = strlen(ctx[i].str);
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- ctx[i].fd = open(ctx[i].path, O_RDONLY);
- if (ctx[i].fd >= 0) {
- fprintf(stderr, "FUSE_WORKLOAD: Error: was able to open %s for read before it "
- "was created!\n", ctx[i].path);
- return -EIO;
- }
- ctx[i].fd = creat(ctx[i].path, 0755);
- if (ctx[i].fd < 0) {
- fprintf(stderr, "FUSE_WORKLOAD: Failed to create file %s for writing!\n",
- ctx[i].path);
- return -EIO;
- }
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- EXPECT_ZERO(safeWrite(ctx[i].fd, ctx[i].str, ctx[i].strLen));
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- EXPECT_ZERO(closeWorkaroundHdfs2551(ctx[i].fd, ctx[i].path, ctx[i].strLen));
- ctx[i].fd = -1;
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- ctx[i].fd = open(ctx[i].path, O_RDONLY);
- if (ctx[i].fd < 0) {
- fprintf(stderr, "FUSE_WORKLOAD: Failed to open file %s for reading!\n",
- ctx[i].path);
- return -EIO;
- }
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- tmpBuf = calloc(1, ctx[i].strLen);
- if (!tmpBuf) {
- fprintf(stderr, "FUSE_WORKLOAD: OOM on line %d\n", __LINE__);
- return -ENOMEM;
- }
- EXPECT_INT_EQ(ctx[i].strLen, safeRead(ctx[i].fd, tmpBuf, ctx[i].strLen));
- EXPECT_ZERO(memcmp(ctx[i].str, tmpBuf, ctx[i].strLen));
- RETRY_ON_EINTR_GET_ERRNO(ret, close(ctx[i].fd));
- ctx[i].fd = -1;
- EXPECT_ZERO(ret);
- free(tmpBuf);
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- EXPECT_ZERO(truncate(ctx[i].path, 0));
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- EXPECT_ZERO(stat(ctx[i].path, &stBuf));
- EXPECT_NONZERO(S_ISREG(stBuf.st_mode));
- EXPECT_INT_EQ(0, stBuf.st_size);
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- RETRY_ON_EINTR_GET_ERRNO(ret, unlink(ctx[i].path));
- EXPECT_ZERO(ret);
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- EXPECT_NEGATIVE_ONE_WITH_ERRNO(stat(ctx[i].path, &stBuf), ENOENT);
- }
- for (i = 0; i < NUM_FILE_CTX; i++) {
- free(ctx[i].path);
- }
- EXPECT_ZERO(testOpenTrunc(base));
- EXPECT_ZERO(recursiveDelete(base));
- return 0;
-}
-
-int runFuseWorkload(const char *root, const char *pcomp)
-{
- int ret, err;
- size_t i;
- char longStr[LONG_STR_LEN];
- struct fileCtx ctx[NUM_FILE_CTX] = {
- {
- .fd = -1,
- .str = "hello, world",
- },
- {
- .fd = -1,
- .str = "A",
- },
- {
- .fd = -1,
- .str = longStr,
- },
- };
- for (i = 0; i < LONG_STR_LEN - 1; i++) {
- longStr[i] = 'a' + (i % 10);
- }
- longStr[LONG_STR_LEN - 1] = '\0';
-
- ret = runFuseWorkloadImpl(root, pcomp, ctx);
- // Make sure all file descriptors are closed, or else we won't be able to
- // unmount
- for (i = 0; i < NUM_FILE_CTX; i++) {
- if (ctx[i].fd >= 0) {
- RETRY_ON_EINTR_GET_ERRNO(err, close(ctx[i].fd));
- }
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/fuse_workload.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/fuse_workload.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/fuse_workload.h
deleted file mode 100644
index 3ff2dc4..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/test/fuse_workload.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef __FUSE_WORKLOAD_H__
-#define __FUSE_WORKLOAD_H__
-
-/**
- * Perform some FUSE operations.
- *
- * The operations will be performed under <root>/<pcomp>.
- * This directory should not exist prior to the test, and should not be used by
- * any other tests concurrently.
- *
- * @param root The root directory for the testing.
- * @param pcomp Path component to add to root
- *
- * @return 0 on success; negative error code otherwise
- */
-int runFuseWorkload(const char *root, const char *pcomp);
-
-#endif
[20/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_users.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_users.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_users.c
new file mode 100644
index 0000000..d7bdfe7
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_users.c
@@ -0,0 +1,213 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+
+#include <pthread.h>
+#include <grp.h>
+#include <pwd.h>
+#include <stdlib.h>
+
+#include "fuse_dfs.h"
+
+/*
+ * getpwuid and getgrgid return static structs so we safeguard the contents
+ * while retrieving fields using the 2 structs below.
+ * NOTE: if using both, always get the passwd struct firt!
+ */
+pthread_mutex_t passwdstruct_mutex = PTHREAD_MUTEX_INITIALIZER;
+pthread_mutex_t groupstruct_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/*
+ * Utility for getting the user making the fuse call in char * form
+ * NOTE: if non-null return, the return must be freed by the caller.
+ */
+char *getUsername(uid_t uid) {
+ //
+ // Critical section - protect from concurrent calls in different threads.
+ // since the struct below is static.
+ // (no returns until end)
+ //
+
+ pthread_mutex_lock(&passwdstruct_mutex);
+
+ struct passwd *userinfo = getpwuid(uid);
+ char * ret = userinfo && userinfo->pw_name ? strdup(userinfo->pw_name) : NULL;
+
+ pthread_mutex_unlock(&passwdstruct_mutex);
+
+ //
+ // End critical section
+ //
+ return ret;
+}
+
+/**
+ * Cleans up a char ** group pointer
+ */
+
+void freeGroups(char **groups, int numgroups) {
+ if (groups == NULL) {
+ return;
+ }
+ int i ;
+ for (i = 0; i < numgroups; i++) {
+ free(groups[i]);
+ }
+ free(groups);
+}
+
+#define GROUPBUF_SIZE 5
+
+char *getGroup(gid_t gid) {
+ //
+ // Critical section - protect from concurrent calls in different threads.
+ // since the struct below is static.
+ // (no returns until end)
+ //
+
+ pthread_mutex_lock(&groupstruct_mutex);
+
+ struct group* grp = getgrgid(gid);
+ char * ret = grp && grp->gr_name ? strdup(grp->gr_name) : NULL;
+
+ //
+ // End critical section
+ //
+ pthread_mutex_unlock(&groupstruct_mutex);
+
+ return ret;
+}
+
+
+/**
+ * Utility for getting the group from the uid
+ * NOTE: if non-null return, the return must be freed by the caller.
+ */
+char *getGroupUid(uid_t uid) {
+ //
+ // Critical section - protect from concurrent calls in different threads
+ // since the structs below are static.
+ // (no returns until end)
+ //
+
+ pthread_mutex_lock(&passwdstruct_mutex);
+ pthread_mutex_lock(&groupstruct_mutex);
+
+ char *ret = NULL;
+ struct passwd *userinfo = getpwuid(uid);
+ if (NULL != userinfo) {
+ struct group* grp = getgrgid( userinfo->pw_gid);
+ ret = grp && grp->gr_name ? strdup(grp->gr_name) : NULL;
+ }
+
+ //
+ // End critical section
+ //
+ pthread_mutex_unlock(&groupstruct_mutex);
+ pthread_mutex_unlock(&passwdstruct_mutex);
+
+ return ret;
+}
+
+
+/**
+ * lookup the gid based on the uid
+ */
+gid_t getGidUid(uid_t uid) {
+ //
+ // Critical section - protect from concurrent calls in different threads
+ // since the struct below is static.
+ // (no returns until end)
+ //
+
+ pthread_mutex_lock(&passwdstruct_mutex);
+
+ struct passwd *userinfo = getpwuid(uid);
+ gid_t gid = userinfo == NULL ? 0 : userinfo->pw_gid;
+
+ //
+ // End critical section
+ //
+ pthread_mutex_unlock(&passwdstruct_mutex);
+
+ return gid;
+}
+
+/**
+ * Utility for getting the groups for the user making the fuse call in char * form
+ */
+char ** getGroups(uid_t uid, int *num_groups)
+{
+ char *user = getUsername(uid);
+
+ if (user == NULL)
+ return NULL;
+
+ char **groupnames = NULL;
+
+ // see http://www.openldap.org/lists/openldap-devel/199903/msg00023.html
+
+ //#define GETGROUPS_T 1
+#ifdef GETGROUPS_T
+ *num_groups = GROUPBUF_SIZE;
+
+ gid_t* grouplist = malloc(GROUPBUF_SIZE * sizeof(gid_t));
+ assert(grouplist != NULL);
+ gid_t* tmp_grouplist;
+ int rtr;
+
+ gid_t gid = getGidUid(uid);
+
+ if ((rtr = getgrouplist(user, gid, grouplist, num_groups)) == -1) {
+ // the buffer we passed in is < *num_groups
+ if ((tmp_grouplist = realloc(grouplist, *num_groups * sizeof(gid_t))) != NULL) {
+ grouplist = tmp_grouplist;
+ getgrouplist(user, gid, grouplist, num_groups);
+ }
+ }
+
+ groupnames = (char**)malloc(sizeof(char*)* (*num_groups) + 1);
+ assert(groupnames);
+ int i;
+ for (i=0; i < *num_groups; i++) {
+ groupnames[i] = getGroup(grouplist[i]);
+ if (groupnames[i] == NULL) {
+ ERROR("Could not lookup group %d\n", (int)grouplist[i]);
+ }
+ }
+ free(grouplist);
+ assert(user != NULL);
+ groupnames[i] = user;
+ *num_groups = *num_groups + 1;
+#else
+
+ int i = 0;
+ assert(user != NULL);
+ groupnames[i] = user;
+ i++;
+
+ groupnames[i] = getGroupUid(uid);
+ if (groupnames[i]) {
+ i++;
+ }
+
+ *num_groups = i;
+
+#endif
+ return groupnames;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_users.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_users.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_users.h
new file mode 100644
index 0000000..d63d916
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_users.h
@@ -0,0 +1,70 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_USERS_H__
+#define __FUSE_USERS_H__
+
+#include <grp.h>
+#include <pwd.h>
+#include <pthread.h>
+
+/**
+ * Overall Note:
+ * 1. all these functions should be thread safe.
+ * 2. the ones that return char * or char **, generally require
+ * the caller to free the return value.
+ *
+ */
+
+
+/**
+ * Utility for getting the user making the fuse call in char * form
+ * NOTE: if non-null return, the return must be freed by the caller.
+ */
+char *getUsername(uid_t uid);
+
+
+/**
+ * Cleans up a char ** group pointer
+ */
+void freeGroups(char **groups, int numgroups);
+
+/**
+ * Lookup single group. Caller responsible for free of the return value
+ */
+char *getGroup(gid_t gid);
+
+/**
+ * Utility for getting the group from the uid
+ * NOTE: if non-null return, the return must be freed by the caller.
+ */
+char *getGroupUid(uid_t uid) ;
+
+
+/**
+ * lookup the gid based on the uid
+ */
+
+gid_t getGidUid(uid_t uid);
+
+/**
+ * Utility for getting the groups for the user making the fuse call in char * form
+ */
+char ** getGroups(uid_t uid, int *num_groups);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/TestFuseDFS.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/TestFuseDFS.java b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/TestFuseDFS.java
new file mode 100644
index 0000000..a5d9abd
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/TestFuseDFS.java
@@ -0,0 +1,410 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import java.io.*;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.concurrent.atomic.*;
+
+import org.apache.log4j.Level;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.*;
+import org.apache.hadoop.fs.permission.*;
+import org.apache.hadoop.hdfs.*;
+import org.apache.hadoop.io.IOUtils;
+import org.apache.hadoop.test.GenericTestUtils;
+import org.apache.hadoop.util.StringUtils;
+
+import org.junit.Test;
+import org.junit.BeforeClass;
+import org.junit.AfterClass;
+import static org.junit.Assert.*;
+
+/**
+ * Basic functional tests on a fuse-dfs mount.
+ */
+public class TestFuseDFS {
+
+ private static MiniDFSCluster cluster;
+ private static FileSystem fs;
+ private static Process fuseProcess;
+ private static Runtime r;
+ private static String mountPoint;
+
+ private static final Log LOG = LogFactory.getLog(TestFuseDFS.class);
+ {
+ GenericTestUtils.setLogLevel(LOG, Level.ALL);
+ }
+
+ /** Dump the given intput stream to stderr */
+ private static void dumpInputStream(InputStream is) throws IOException {
+ int len;
+ do {
+ byte b[] = new byte[is.available()];
+ len = is.read(b);
+ System.out.println("Read "+len+" bytes");
+ System.out.write(b, 0, b.length);
+ } while (len > 0);
+ }
+
+ /**
+ * Wait for the given process to return and check that it exited
+ * as required. Log if the process failed.
+ */
+ private static void checkProcessRet(Process p, boolean expectPass)
+ throws IOException {
+ try {
+ int ret = p.waitFor();
+ if (ret != 0) {
+ dumpInputStream(p.getErrorStream());
+ }
+ if (expectPass) {
+ assertEquals(0, ret);
+ } else {
+ assertTrue(ret != 0);
+ }
+ } catch (InterruptedException ie) {
+ fail("Process interrupted: "+ie.getMessage());
+ }
+ }
+
+ /** Exec the given command and assert it executed successfully */
+ private static void execWaitRet(String cmd) throws IOException {
+ LOG.debug("EXEC "+cmd);
+ Process p = r.exec(cmd);
+ try {
+ p.waitFor();
+ } catch (InterruptedException ie) {
+ fail("Process interrupted: "+ie.getMessage());
+ }
+ }
+
+ /** Exec the given command and assert it executed successfully */
+ private static void execIgnoreRet(String cmd) throws IOException {
+ LOG.debug("EXEC "+cmd);
+ r.exec(cmd);
+ }
+
+ /** Exec the given command and assert it executed successfully */
+ private static void execAssertSucceeds(String cmd) throws IOException {
+ LOG.debug("EXEC "+cmd);
+ checkProcessRet(r.exec(cmd), true);
+ }
+
+ /** Exec the given command, assert it returned an error code */
+ private static void execAssertFails(String cmd) throws IOException {
+ LOG.debug("EXEC "+cmd);
+ checkProcessRet(r.exec(cmd), false);
+ }
+
+ /** Create and write the given file */
+ private static void createFile(File f, String s) throws IOException {
+ InputStream is = new ByteArrayInputStream(s.getBytes());
+ FileOutputStream fos = new FileOutputStream(f);
+ IOUtils.copyBytes(is, fos, s.length(), true);
+ }
+
+ /** Check that the given file exists with the given contents */
+ private static void checkFile(File f, String expectedContents)
+ throws IOException {
+ FileInputStream fi = new FileInputStream(f);
+ int len = expectedContents.length();
+ byte[] b = new byte[len];
+ try {
+ IOUtils.readFully(fi, b, 0, len);
+ } catch (IOException ie) {
+ fail("Reading "+f.getName()+" failed with "+ie.getMessage());
+ } finally {
+ fi.close(); // NB: leaving f unclosed prevents unmount
+ }
+ String s = new String(b, 0, len);
+ assertEquals("File content differs", expectedContents, s);
+ }
+
+ private static class RedirectToStdoutThread extends Thread {
+ private InputStream is;
+
+ RedirectToStdoutThread(InputStream is) {
+ this.is = is;
+ }
+ public void run() {
+ try {
+ InputStreamReader isr = new InputStreamReader(is);
+ BufferedReader br = new BufferedReader(isr);
+ String line=null;
+ while ( (line = br.readLine()) != null) {
+ LOG.error("FUSE_LINE:" + line);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /** Run a fuse-dfs process to mount the given DFS */
+ private static Process establishMount(URI uri) throws IOException {
+ Runtime r = Runtime.getRuntime();
+ String cp = System.getProperty("java.class.path");
+
+ String buildTestDir = System.getProperty("build.test");
+ String fuseCmd = buildTestDir + "/../fuse_dfs";
+ String libHdfs = buildTestDir + "/../../../c++/lib";
+
+ String arch = System.getProperty("os.arch");
+ String jvm = System.getProperty("java.home") + "/lib/" + arch + "/server";
+ String lp = System.getProperty("LD_LIBRARY_PATH")+":"+libHdfs+":"+jvm;
+ LOG.debug("LD_LIBRARY_PATH=" + lp);
+
+ String nameNode =
+ "dfs://" + uri.getHost() + ":" + String.valueOf(uri.getPort());
+
+ // NB: We're mounting via an unprivileged user, therefore
+ // user_allow_other needs to be set in /etc/fuse.conf, which also
+ // needs to be world readable.
+ String mountCmd[] = {
+ fuseCmd, nameNode, mountPoint,
+ // "-odebug", // Don't daemonize
+ "-obig_writes", // Allow >4kb writes
+ "-oentry_timeout=0.1", // Don't cache dents long
+ "-oattribute_timeout=0.1", // Don't cache attributes long
+ "-ononempty", // Don't complain about junk in mount point
+ "-f", // Don't background the process
+ "-ordbuffer=32768", // Read buffer size in kb
+ "rw"
+ };
+
+ String [] env = {
+ "CLASSPATH="+cp,
+ "LD_LIBRARY_PATH="+lp,
+ "PATH=/usr/bin:/bin"
+ };
+
+ execWaitRet("fusermount -u " + mountPoint);
+ execAssertSucceeds("rm -rf " + mountPoint);
+ execAssertSucceeds("mkdir -p " + mountPoint);
+
+ // Mount the mini cluster
+ String cmdStr = "";
+ for (String c : mountCmd) {
+ cmdStr += (" " + c);
+ }
+ LOG.info("now mounting with:" + cmdStr);
+ Process fuseProcess = r.exec(mountCmd, env);
+ RedirectToStdoutThread stdoutThread =
+ new RedirectToStdoutThread(fuseProcess.getInputStream());
+ RedirectToStdoutThread stderrThread =
+ new RedirectToStdoutThread(fuseProcess.getErrorStream());
+ stdoutThread.start();
+ stderrThread.start();
+ // Wait for fusermount to start up, so that we know we're operating on the
+ // FUSE FS when we run the tests.
+ try {
+ Thread.sleep(50000);
+ } catch (InterruptedException e) {
+ }
+ return fuseProcess;
+ }
+
+ /** Tear down the fuse-dfs process and mount */
+ private static void teardownMount() throws IOException {
+ execWaitRet("fusermount -u " + mountPoint);
+ try {
+ assertEquals(0, fuseProcess.waitFor()); // fuse_dfs should exit cleanly
+ } catch (InterruptedException e) {
+ fail("interrupted while waiting for fuse_dfs process to exit.");
+ }
+ }
+
+ @BeforeClass
+ public static void startUp() throws IOException {
+ Configuration conf = new HdfsConfiguration();
+ r = Runtime.getRuntime();
+ mountPoint = System.getProperty("build.test") + "/mnt";
+ conf.setBoolean(DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY, false);
+ cluster = new MiniDFSCluster.Builder(conf).build();
+ cluster.waitClusterUp();
+ fs = cluster.getFileSystem();
+ fuseProcess = establishMount(fs.getUri());
+ }
+
+ @AfterClass
+ public static void tearDown() throws IOException {
+ // Unmount before taking down the mini cluster
+ // so no outstanding operations hang.
+ teardownMount();
+ if (fs != null) {
+ fs.close();
+ }
+ if (cluster != null) {
+ cluster.shutdown();
+ }
+ }
+
+ /** Test basic directory creation, access, removal */
+ @Test
+ public void testBasicDir() throws IOException {
+ File d = new File(mountPoint, "dir1");
+
+ // Mkdir, access and rm via the mount
+ execAssertSucceeds("mkdir " + d.getAbsolutePath());
+ execAssertSucceeds("ls " + d.getAbsolutePath());
+ execAssertSucceeds("rmdir " + d.getAbsolutePath());
+
+ // The dir should no longer exist
+ execAssertFails("ls " + d.getAbsolutePath());
+ }
+
+ /** Test basic file creation and writing */
+ @Test
+ public void testCreate() throws IOException {
+ final String contents = "hello world";
+ File f = new File(mountPoint, "file1");
+
+ // Create and access via the mount
+ createFile(f, contents);
+
+ // XX avoids premature EOF
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException ie) { }
+
+ checkFile(f, contents);
+
+ // Cat, stat and delete via the mount
+ execAssertSucceeds("cat " + f.getAbsolutePath());
+ execAssertSucceeds("stat " + f.getAbsolutePath());
+ execAssertSucceeds("rm " + f.getAbsolutePath());
+
+ // The file should no longer exist
+ execAssertFails("ls " + f.getAbsolutePath());
+ }
+
+ /** Test creating a file via touch */
+ @Test
+ public void testTouch() throws IOException {
+ File f = new File(mountPoint, "file1");
+ execAssertSucceeds("touch " + f.getAbsolutePath());
+ execAssertSucceeds("rm " + f.getAbsolutePath());
+ }
+
+ /** Test random access to a file */
+ @Test
+ public void testRandomAccess() throws IOException {
+ final String contents = "hello world";
+ File f = new File(mountPoint, "file1");
+
+ createFile(f, contents);
+
+ RandomAccessFile raf = new RandomAccessFile(f, "rw");
+ raf.seek(f.length());
+ try {
+ raf.write('b');
+ } catch (IOException e) {
+ // Expected: fuse-dfs not yet support append
+ assertEquals("Operation not supported", e.getMessage());
+ } finally {
+ raf.close();
+ }
+
+ raf = new RandomAccessFile(f, "rw");
+ raf.seek(0);
+ try {
+ raf.write('b');
+ fail("Over-wrote existing bytes");
+ } catch (IOException e) {
+ // Expected: can-not overwrite a file
+ assertEquals("Invalid argument", e.getMessage());
+ } finally {
+ raf.close();
+ }
+ execAssertSucceeds("rm " + f.getAbsolutePath());
+ }
+
+ /** Test copying a set of files from the mount to itself */
+ @Test
+ public void testCopyFiles() throws IOException {
+ final String contents = "hello world";
+ File d1 = new File(mountPoint, "dir1");
+ File d2 = new File(mountPoint, "dir2");
+
+ // Create and populate dir1 via the mount
+ execAssertSucceeds("mkdir " + d1.getAbsolutePath());
+ for (int i = 0; i < 5; i++) {
+ createFile(new File(d1, "file"+i), contents);
+ }
+ assertEquals(5, d1.listFiles().length);
+
+ // Copy dir from the mount to the mount
+ execAssertSucceeds("cp -r " + d1.getAbsolutePath() +
+ " " + d2.getAbsolutePath());
+ assertEquals(5, d2.listFiles().length);
+
+ // Access all the files in the dirs and remove them
+ execAssertSucceeds("find " + d1.getAbsolutePath());
+ execAssertSucceeds("find " + d2.getAbsolutePath());
+ execAssertSucceeds("rm -r " + d1.getAbsolutePath());
+ execAssertSucceeds("rm -r " + d2.getAbsolutePath());
+ }
+
+ /** Test concurrent creation and access of the mount */
+ @Test
+ public void testMultipleThreads() throws IOException {
+ ArrayList<Thread> threads = new ArrayList<Thread>();
+ final AtomicReference<String> errorMessage = new AtomicReference<String>();
+
+ for (int i = 0; i < 10; i++) {
+ Thread t = new Thread() {
+ public void run() {
+ try {
+ File d = new File(mountPoint, "dir"+getId());
+ execWaitRet("mkdir " + d.getAbsolutePath());
+ for (int j = 0; j < 10; j++) {
+ File f = new File(d, "file"+j);
+ final String contents = "thread "+getId()+" "+j;
+ createFile(f, contents);
+ }
+ for (int j = 0; j < 10; j++) {
+ File f = new File(d, "file"+j);
+ execWaitRet("cat " + f.getAbsolutePath());
+ execWaitRet("rm " + f.getAbsolutePath());
+ }
+ execWaitRet("rmdir " + d.getAbsolutePath());
+ } catch (IOException ie) {
+ errorMessage.set(
+ String.format("Exception %s",
+ StringUtils.stringifyException(ie)));
+ }
+ }
+ };
+ t.start();
+ threads.add(t);
+ }
+
+ for (Thread t : threads) {
+ try {
+ t.join();
+ } catch (InterruptedException ie) {
+ fail("Thread interrupted: "+ie.getMessage());
+ }
+ }
+
+ assertNull(errorMessage.get(), errorMessage.get());
+ }
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/fuse_workload.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/fuse_workload.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/fuse_workload.c
new file mode 100644
index 0000000..78fdbc6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/fuse_workload.c
@@ -0,0 +1,403 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#define FUSE_USE_VERSION 26
+
+#include "fuse-dfs/test/fuse_workload.h"
+#include "libhdfs/expect.h"
+#include "util/posix_util.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fuse.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/statvfs.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <utime.h>
+
+typedef int (*testReadDirFn)(const struct dirent *de, void *v);
+
+struct fileCtx {
+ int fd;
+ char *str;
+ int strLen;
+ char *path;
+};
+
+static const char *DIRS_A_AND_B[] = { "a", "b", NULL };
+static const char *DIRS_B_AND_C[] = { "b", "c", NULL };
+
+#define LONG_STR_LEN 1024
+#define NUM_FILE_CTX 3
+#define MAX_TRIES 120
+
+// TODO: implement/test access, mknod, symlink
+// TODO: rmdir on non-dir, non-empty dir
+// TODO: test unlink-during-writing
+// TODO: test weird open flags failing
+// TODO: test chown, chmod
+
+static int testReadDirImpl(DIR *dp, testReadDirFn fn, void *data)
+{
+ struct dirent *de;
+ int ret, noda = 0;
+
+ while (1) {
+ de = readdir(dp);
+ if (!de)
+ return noda;
+ if (!strcmp(de->d_name, "."))
+ continue;
+ if (!strcmp(de->d_name, ".."))
+ continue;
+ ret = fn(de, data);
+ if (ret < 0)
+ return ret;
+ ++noda;
+ }
+ return noda;
+}
+
+static int testReadDir(const char *dirName, testReadDirFn fn, void *data)
+{
+ int ret;
+ DIR *dp;
+
+ dp = opendir(dirName);
+ if (!dp) {
+ return -errno;
+ }
+ ret = testReadDirImpl(dp, fn, data);
+ closedir(dp);
+ return ret;
+}
+
+static int expectDirs(const struct dirent *de, void *v)
+{
+ const char **names = v;
+ const char **n;
+
+ for (n = names; *n; ++n) {
+ if (!strcmp(de->d_name, *n)) {
+ return 0;
+ }
+ }
+ return -ENOENT;
+}
+
+static int safeWrite(int fd, const void *buf, size_t amt)
+{
+ while (amt > 0) {
+ int r = write(fd, buf, amt);
+ if (r < 0) {
+ if (errno != EINTR)
+ return -errno;
+ continue;
+ }
+ amt -= r;
+ buf = (const char *)buf + r;
+ }
+ return 0;
+}
+
+static int safeRead(int fd, void *buf, int c)
+{
+ int res;
+ size_t amt = 0;
+
+ while (amt < c) {
+ res = read(fd, buf, c - amt);
+ if (res <= 0) {
+ if (res == 0)
+ return amt;
+ if (errno != EINTR)
+ return -errno;
+ continue;
+ }
+ amt += res;
+ buf = (char *)buf + res;
+ }
+ return amt;
+}
+
+/* Bug: HDFS-2551.
+ * When a program writes a file, closes it, and immediately re-opens it,
+ * it might not appear to have the correct length. This is because FUSE
+ * invokes the release() callback asynchronously.
+ *
+ * To work around this, we keep retrying until the file length is what we
+ * expect.
+ */
+static int closeWorkaroundHdfs2551(int fd, const char *path, off_t expectedSize)
+{
+ int ret, try;
+ struct stat stBuf;
+
+ RETRY_ON_EINTR_GET_ERRNO(ret, close(fd));
+ EXPECT_ZERO(ret);
+ for (try = 0; try < MAX_TRIES; try++) {
+ EXPECT_ZERO(stat(path, &stBuf));
+ EXPECT_NONZERO(S_ISREG(stBuf.st_mode));
+ if (stBuf.st_size == expectedSize) {
+ return 0;
+ }
+ sleepNoSig(1);
+ }
+ fprintf(stderr, "FUSE_WORKLOAD: error: expected file %s to have length "
+ "%lld; instead, it had length %lld\n",
+ path, (long long)expectedSize, (long long)stBuf.st_size);
+ return -EIO;
+}
+
+#ifdef FUSE_CAP_ATOMIC_O_TRUNC
+
+/**
+ * Test that we can create a file, write some contents to it, close that file,
+ * and then successfully re-open with O_TRUNC.
+ */
+static int testOpenTrunc(const char *base)
+{
+ int fd, err;
+ char path[PATH_MAX];
+ const char * const SAMPLE1 = "this is the first file that we wrote.";
+ const char * const SAMPLE2 = "this is the second file that we wrote. "
+ "It's #2!";
+
+ snprintf(path, sizeof(path), "%s/trunc.txt", base);
+ fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0644);
+ if (fd < 0) {
+ err = errno;
+ fprintf(stderr, "TEST_ERROR: testOpenTrunc(%s): first open "
+ "failed with error %d\n", path, err);
+ return -err;
+ }
+ EXPECT_ZERO(safeWrite(fd, SAMPLE1, strlen(SAMPLE1)));
+ EXPECT_ZERO(closeWorkaroundHdfs2551(fd, path, strlen(SAMPLE1)));
+ fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0644);
+ if (fd < 0) {
+ err = errno;
+ fprintf(stderr, "TEST_ERROR: testOpenTrunc(%s): second open "
+ "failed with error %d\n", path, err);
+ return -err;
+ }
+ EXPECT_ZERO(safeWrite(fd, SAMPLE2, strlen(SAMPLE2)));
+ EXPECT_ZERO(closeWorkaroundHdfs2551(fd, path, strlen(SAMPLE2)));
+ return 0;
+}
+
+#else
+
+static int testOpenTrunc(const char *base)
+{
+ fprintf(stderr, "FUSE_WORKLOAD: We lack FUSE_CAP_ATOMIC_O_TRUNC support. "
+ "Not testing open(O_TRUNC).\n");
+ return 0;
+}
+
+#endif
+
+int runFuseWorkloadImpl(const char *root, const char *pcomp,
+ struct fileCtx *ctx)
+{
+ char base[PATH_MAX], tmp[PATH_MAX], *tmpBuf;
+ char src[PATH_MAX], dst[PATH_MAX];
+ struct stat stBuf;
+ int ret, i;
+ struct utimbuf tbuf;
+ struct statvfs stvBuf;
+
+ // The root must be a directory
+ EXPECT_ZERO(stat(root, &stBuf));
+ EXPECT_NONZERO(S_ISDIR(stBuf.st_mode));
+
+ // base = <root>/<pcomp>. base must not exist yet
+ snprintf(base, sizeof(base), "%s/%s", root, pcomp);
+ EXPECT_NEGATIVE_ONE_WITH_ERRNO(stat(base, &stBuf), ENOENT);
+
+ // mkdir <base>
+ RETRY_ON_EINTR_GET_ERRNO(ret, mkdir(base, 0755));
+ EXPECT_ZERO(ret);
+
+ // rmdir <base>
+ RETRY_ON_EINTR_GET_ERRNO(ret, rmdir(base));
+ EXPECT_ZERO(ret);
+
+ // mkdir <base>
+ RETRY_ON_EINTR_GET_ERRNO(ret, mkdir(base, 0755));
+ EXPECT_ZERO(ret);
+
+ // stat <base>
+ EXPECT_ZERO(stat(base, &stBuf));
+ EXPECT_NONZERO(S_ISDIR(stBuf.st_mode));
+
+ // mkdir <base>/a
+ snprintf(tmp, sizeof(tmp), "%s/a", base);
+ RETRY_ON_EINTR_GET_ERRNO(ret, mkdir(tmp, 0755));
+ EXPECT_ZERO(ret);
+
+ /* readdir test */
+ EXPECT_INT_EQ(1, testReadDir(base, expectDirs, DIRS_A_AND_B));
+
+ // mkdir <base>/b
+ snprintf(tmp, sizeof(tmp), "%s/b", base);
+ RETRY_ON_EINTR_GET_ERRNO(ret, mkdir(tmp, 0755));
+ EXPECT_ZERO(ret);
+
+ // readdir a and b
+ EXPECT_INT_EQ(2, testReadDir(base, expectDirs, DIRS_A_AND_B));
+
+ // rename a -> c
+ snprintf(src, sizeof(src), "%s/a", base);
+ snprintf(dst, sizeof(dst), "%s/c", base);
+ EXPECT_ZERO(rename(src, dst));
+
+ // readdir c and b
+ EXPECT_INT_EQ(-ENOENT, testReadDir(base, expectDirs, DIRS_A_AND_B));
+ EXPECT_INT_EQ(2, testReadDir(base, expectDirs, DIRS_B_AND_C));
+
+ // statvfs
+ memset(&stvBuf, 0, sizeof(stvBuf));
+ EXPECT_ZERO(statvfs(root, &stvBuf));
+
+ // set utime on base
+ memset(&tbuf, 0, sizeof(tbuf));
+ tbuf.actime = 123;
+ tbuf.modtime = 456;
+ EXPECT_ZERO(utime(base, &tbuf));
+
+ // stat(base)
+ EXPECT_ZERO(stat(base, &stBuf));
+ EXPECT_NONZERO(S_ISDIR(stBuf.st_mode));
+ //EXPECT_INT_EQ(456, stBuf.st_atime); // hdfs doesn't store atime on directories
+ EXPECT_INT_EQ(456, stBuf.st_mtime);
+
+ // open some files and write to them
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ snprintf(tmp, sizeof(tmp), "%s/b/%d", base, i);
+ ctx[i].path = strdup(tmp);
+ if (!ctx[i].path) {
+ fprintf(stderr, "FUSE_WORKLOAD: OOM on line %d\n", __LINE__);
+ return -ENOMEM;
+ }
+ ctx[i].strLen = strlen(ctx[i].str);
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ ctx[i].fd = open(ctx[i].path, O_RDONLY);
+ if (ctx[i].fd >= 0) {
+ fprintf(stderr, "FUSE_WORKLOAD: Error: was able to open %s for read before it "
+ "was created!\n", ctx[i].path);
+ return -EIO;
+ }
+ ctx[i].fd = creat(ctx[i].path, 0755);
+ if (ctx[i].fd < 0) {
+ fprintf(stderr, "FUSE_WORKLOAD: Failed to create file %s for writing!\n",
+ ctx[i].path);
+ return -EIO;
+ }
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ EXPECT_ZERO(safeWrite(ctx[i].fd, ctx[i].str, ctx[i].strLen));
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ EXPECT_ZERO(closeWorkaroundHdfs2551(ctx[i].fd, ctx[i].path, ctx[i].strLen));
+ ctx[i].fd = -1;
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ ctx[i].fd = open(ctx[i].path, O_RDONLY);
+ if (ctx[i].fd < 0) {
+ fprintf(stderr, "FUSE_WORKLOAD: Failed to open file %s for reading!\n",
+ ctx[i].path);
+ return -EIO;
+ }
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ tmpBuf = calloc(1, ctx[i].strLen);
+ if (!tmpBuf) {
+ fprintf(stderr, "FUSE_WORKLOAD: OOM on line %d\n", __LINE__);
+ return -ENOMEM;
+ }
+ EXPECT_INT_EQ(ctx[i].strLen, safeRead(ctx[i].fd, tmpBuf, ctx[i].strLen));
+ EXPECT_ZERO(memcmp(ctx[i].str, tmpBuf, ctx[i].strLen));
+ RETRY_ON_EINTR_GET_ERRNO(ret, close(ctx[i].fd));
+ ctx[i].fd = -1;
+ EXPECT_ZERO(ret);
+ free(tmpBuf);
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ EXPECT_ZERO(truncate(ctx[i].path, 0));
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ EXPECT_ZERO(stat(ctx[i].path, &stBuf));
+ EXPECT_NONZERO(S_ISREG(stBuf.st_mode));
+ EXPECT_INT_EQ(0, stBuf.st_size);
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ RETRY_ON_EINTR_GET_ERRNO(ret, unlink(ctx[i].path));
+ EXPECT_ZERO(ret);
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ EXPECT_NEGATIVE_ONE_WITH_ERRNO(stat(ctx[i].path, &stBuf), ENOENT);
+ }
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ free(ctx[i].path);
+ }
+ EXPECT_ZERO(testOpenTrunc(base));
+ EXPECT_ZERO(recursiveDelete(base));
+ return 0;
+}
+
+int runFuseWorkload(const char *root, const char *pcomp)
+{
+ int ret, err;
+ size_t i;
+ char longStr[LONG_STR_LEN];
+ struct fileCtx ctx[NUM_FILE_CTX] = {
+ {
+ .fd = -1,
+ .str = "hello, world",
+ },
+ {
+ .fd = -1,
+ .str = "A",
+ },
+ {
+ .fd = -1,
+ .str = longStr,
+ },
+ };
+ for (i = 0; i < LONG_STR_LEN - 1; i++) {
+ longStr[i] = 'a' + (i % 10);
+ }
+ longStr[LONG_STR_LEN - 1] = '\0';
+
+ ret = runFuseWorkloadImpl(root, pcomp, ctx);
+ // Make sure all file descriptors are closed, or else we won't be able to
+ // unmount
+ for (i = 0; i < NUM_FILE_CTX; i++) {
+ if (ctx[i].fd >= 0) {
+ RETRY_ON_EINTR_GET_ERRNO(err, close(ctx[i].fd));
+ }
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/fuse_workload.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/fuse_workload.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/fuse_workload.h
new file mode 100644
index 0000000..3ff2dc4
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/fuse_workload.h
@@ -0,0 +1,36 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_WORKLOAD_H__
+#define __FUSE_WORKLOAD_H__
+
+/**
+ * Perform some FUSE operations.
+ *
+ * The operations will be performed under <root>/<pcomp>.
+ * This directory should not exist prior to the test, and should not be used by
+ * any other tests concurrently.
+ *
+ * @param root The root directory for the testing.
+ * @param pcomp Path component to add to root
+ *
+ * @return 0 on success; negative error code otherwise
+ */
+int runFuseWorkload(const char *root, const char *pcomp);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/test_fuse_dfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/test_fuse_dfs.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/test_fuse_dfs.c
new file mode 100644
index 0000000..f4212a6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/test/test_fuse_dfs.c
@@ -0,0 +1,378 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse-dfs/test/fuse_workload.h"
+#include "libhdfs/expect.h"
+#include "libhdfs/hdfs.h"
+#include "libhdfs/native_mini_dfs.h"
+#include "util/posix_util.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <libgen.h>
+#include <limits.h>
+#include <mntent.h>
+#include <semaphore.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+/** Exit status to return when there is an exec error.
+ *
+ * We assume that fusermount and fuse_dfs don't normally return this error code.
+ */
+#define EXIT_STATUS_EXEC_ERROR 240
+
+/** Maximum number of times to try to unmount the fuse filesystem we created.
+ */
+#define MAX_UNMOUNT_TRIES 20
+
+/**
+ * Verify that the fuse workload works on the local FS.
+ *
+ * @return 0 on success; error code otherwise
+ */
+static int verifyFuseWorkload(void)
+{
+ char tempDir[PATH_MAX];
+
+ EXPECT_ZERO(createTempDir(tempDir, sizeof(tempDir), 0755));
+ EXPECT_ZERO(runFuseWorkload(tempDir, "test"));
+ EXPECT_ZERO(recursiveDelete(tempDir));
+
+ return 0;
+}
+
+static int fuserMount(int *procRet, ...) __attribute__((sentinel));
+
+/**
+ * Invoke the fusermount binary.
+ *
+ * @param retVal (out param) The return value from fusermount
+ *
+ * @return 0 on success; error code if the fork fails
+ */
+static int fuserMount(int *procRet, ...)
+{
+ int ret, status;
+ size_t i = 0;
+ char *args[64], *c;
+ va_list ap;
+ pid_t pid, pret;
+
+ args[i++] = "fusermount";
+ va_start(ap, procRet);
+ while (1) {
+ c = va_arg(ap, char *);
+ args[i++] = c;
+ if (!c)
+ break;
+ if (i > sizeof(args)/sizeof(args[0])) {
+ va_end(ap);
+ return -EINVAL;
+ }
+ }
+ va_end(ap);
+ pid = fork();
+ if (pid < 0) {
+ ret = errno;
+ fprintf(stderr, "FUSE_TEST: failed to fork: error %d: %s\n",
+ ret, strerror(ret));
+ return -ret;
+ } else if (pid == 0) {
+ if (execvp("fusermount", args)) {
+ ret = errno;
+ fprintf(stderr, "FUSE_TEST: failed to execute fusermount: "
+ "error %d: %s\n", ret, strerror(ret));
+ exit(EXIT_STATUS_EXEC_ERROR);
+ }
+ }
+ pret = waitpid(pid, &status, 0);
+ if (pret != pid) {
+ ret = errno;
+ fprintf(stderr, "FUSE_TEST: failed to wait for pid %d: returned %d "
+ "(error %d: %s)\n", pid, pret, ret, strerror(ret));
+ return -ret;
+ }
+ if (WIFEXITED(status)) {
+ *procRet = WEXITSTATUS(status);
+ } else if (WIFSIGNALED(status)) {
+ fprintf(stderr, "FUSE_TEST: fusermount exited with signal %d\n",
+ WTERMSIG(status));
+ *procRet = -1;
+ } else {
+ fprintf(stderr, "FUSE_TEST: fusermount exited with unknown exit type\n");
+ *procRet = -1;
+ }
+ return 0;
+}
+
+static int isMounted(const char *mntPoint)
+{
+ int ret;
+ FILE *fp;
+ struct mntent *mntEnt;
+
+ fp = setmntent("/proc/mounts", "r");
+ if (!fp) {
+ ret = errno;
+ fprintf(stderr, "FUSE_TEST: isMounted(%s) failed to open /proc/mounts: "
+ "error %d: %s", mntPoint, ret, strerror(ret));
+ return -ret;
+ }
+ while ((mntEnt = getmntent(fp))) {
+ if (!strcmp(mntEnt->mnt_dir, mntPoint)) {
+ endmntent(fp);
+ return 1;
+ }
+ }
+ endmntent(fp);
+ return 0;
+}
+
+static int waitForMount(const char *mntPoint, int retries)
+{
+ int ret, try = 0;
+
+ while (try++ < retries) {
+ ret = isMounted(mntPoint);
+ if (ret < 0) {
+ fprintf(stderr, "FUSE_TEST: waitForMount(%s, %d): isMounted returned "
+ "error %d\n", mntPoint, retries, ret);
+ } else if (ret == 1) {
+ return 0;
+ }
+ sleepNoSig(2);
+ }
+ return -ETIMEDOUT;
+}
+
+/**
+ * Try to unmount the fuse filesystem we mounted.
+ *
+ * Normally, only one try should be sufficient to unmount the filesystem.
+ * However, if our tests needs to exit right after starting the fuse_dfs process,
+ * the fuse_dfs process might not have gotten around to mounting itself yet. The
+ * retry loop in this function ensures that we always unmount FUSE before
+ * exiting, rather than leaving around a zombie fuse_dfs.
+ *
+ * @param mntPoint Where the FUSE filesystem is mounted
+ * @return 0 on success; error code otherwise
+ */
+static int cleanupFuse(const char *mntPoint)
+{
+ int ret, pret, tries = 0;
+
+ while (1) {
+ ret = fuserMount(&pret, "-u", mntPoint, NULL);
+ if (ret) {
+ fprintf(stderr, "FUSE_TEST: unmountFuse: failed to invoke fuserMount: "
+ "error %d\n", ret);
+ return ret;
+ }
+ if (pret == 0) {
+ fprintf(stderr, "FUSE_TEST: successfully unmounted FUSE filesystem.\n");
+ return 0;
+ }
+ if (tries++ > MAX_UNMOUNT_TRIES) {
+ return -EIO;
+ }
+ fprintf(stderr, "FUSE_TEST: retrying unmount in 2 seconds...\n");
+ sleepNoSig(2);
+ }
+}
+
+/**
+ * Create a fuse_dfs process using the miniDfsCluster we set up.
+ *
+ * @param argv0 argv[0], as passed into main
+ * @param cluster The NativeMiniDfsCluster to connect to
+ * @param mntPoint The mount point
+ * @param pid (out param) the fuse_dfs process
+ *
+ * @return 0 on success; error code otherwise
+ */
+static int spawnFuseServer(const char *argv0,
+ const struct NativeMiniDfsCluster *cluster, const char *mntPoint,
+ pid_t *pid)
+{
+ int ret, procRet;
+ char scratch[PATH_MAX], *dir, fusePath[PATH_MAX], portOpt[128];
+
+ snprintf(scratch, sizeof(scratch), "%s", argv0);
+ dir = dirname(scratch);
+ snprintf(fusePath, sizeof(fusePath), "%s/fuse_dfs", dir);
+ if (access(fusePath, X_OK)) {
+ fprintf(stderr, "FUSE_TEST: spawnFuseServer: failed to find fuse_dfs "
+ "binary at %s!\n", fusePath);
+ return -ENOENT;
+ }
+ /* Let's make sure no other FUSE filesystem is mounted at mntPoint */
+ ret = fuserMount(&procRet, "-u", mntPoint, NULL);
+ if (ret) {
+ fprintf(stderr, "FUSE_TEST: fuserMount -u %s failed with error %d\n",
+ mntPoint, ret);
+ return -EIO;
+ }
+ if (procRet == EXIT_STATUS_EXEC_ERROR) {
+ fprintf(stderr, "FUSE_TEST: fuserMount probably could not be executed\n");
+ return -EIO;
+ }
+ /* fork and exec the fuse_dfs process */
+ *pid = fork();
+ if (*pid < 0) {
+ ret = errno;
+ fprintf(stderr, "FUSE_TEST: spawnFuseServer: failed to fork: "
+ "error %d: %s\n", ret, strerror(ret));
+ return -ret;
+ } else if (*pid == 0) {
+ snprintf(portOpt, sizeof(portOpt), "-oport=%d",
+ nmdGetNameNodePort(cluster));
+ if (execl(fusePath, fusePath, "-obig_writes", "-oserver=hdfs://localhost",
+ portOpt, "-onopermissions", "-ononempty", "-oinitchecks",
+ mntPoint, "-f", NULL)) {
+ ret = errno;
+ fprintf(stderr, "FUSE_TEST: spawnFuseServer: failed to execv %s: "
+ "error %d: %s\n", fusePath, ret, strerror(ret));
+ exit(EXIT_STATUS_EXEC_ERROR);
+ }
+ }
+ return 0;
+}
+
+/**
+ * Test that we can start up fuse_dfs and do some stuff.
+ */
+int main(int argc, char **argv)
+{
+ int ret, pret, status;
+ pid_t fusePid;
+ const char *mntPoint;
+ char mntTmp[PATH_MAX] = "";
+ struct NativeMiniDfsCluster* tlhCluster;
+ struct NativeMiniDfsConf conf = {
+ .doFormat = 1,
+ };
+
+ mntPoint = getenv("TLH_FUSE_MNT_POINT");
+ if (!mntPoint) {
+ if (createTempDir(mntTmp, sizeof(mntTmp), 0755)) {
+ fprintf(stderr, "FUSE_TEST: failed to create temporary directory for "
+ "fuse mount point.\n");
+ ret = EXIT_FAILURE;
+ goto done;
+ }
+ fprintf(stderr, "FUSE_TEST: creating mount point at '%s'\n", mntTmp);
+ mntPoint = mntTmp;
+ }
+ if (verifyFuseWorkload()) {
+ fprintf(stderr, "FUSE_TEST: failed to verify fuse workload on "
+ "local FS.\n");
+ ret = EXIT_FAILURE;
+ goto done_rmdir;
+ }
+ tlhCluster = nmdCreate(&conf);
+ if (!tlhCluster) {
+ ret = EXIT_FAILURE;
+ goto done_rmdir;
+ }
+ if (nmdWaitClusterUp(tlhCluster)) {
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ ret = spawnFuseServer(argv[0], tlhCluster, mntPoint, &fusePid);
+ if (ret) {
+ fprintf(stderr, "FUSE_TEST: spawnFuseServer failed with error "
+ "code %d\n", ret);
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ ret = waitForMount(mntPoint, 20);
+ if (ret) {
+ fprintf(stderr, "FUSE_TEST: waitForMount(%s) failed with error "
+ "code %d\n", mntPoint, ret);
+ cleanupFuse(mntPoint);
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ ret = runFuseWorkload(mntPoint, "test");
+ if (ret) {
+ fprintf(stderr, "FUSE_TEST: runFuseWorkload failed with error "
+ "code %d\n", ret);
+ cleanupFuse(mntPoint);
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ if (cleanupFuse(mntPoint)) {
+ fprintf(stderr, "FUSE_TEST: fuserMount -u %s failed with error "
+ "code %d\n", mntPoint, ret);
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ alarm(120);
+ pret = waitpid(fusePid, &status, 0);
+ if (pret != fusePid) {
+ ret = errno;
+ fprintf(stderr, "FUSE_TEST: failed to wait for fusePid %d: "
+ "returned %d: error %d (%s)\n",
+ fusePid, pret, ret, strerror(ret));
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ if (WIFEXITED(status)) {
+ ret = WEXITSTATUS(status);
+ if (ret) {
+ fprintf(stderr, "FUSE_TEST: fuse exited with failure status "
+ "%d!\n", ret);
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ } else if (WIFSIGNALED(status)) {
+ ret = WTERMSIG(status);
+ if (ret != SIGTERM) {
+ fprintf(stderr, "FUSE_TEST: fuse exited with unexpected "
+ "signal %d!\n", ret);
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ } else {
+ fprintf(stderr, "FUSE_TEST: fusermount exited with unknown exit type\n");
+ ret = EXIT_FAILURE;
+ goto done_nmd_shutdown;
+ }
+ ret = EXIT_SUCCESS;
+
+done_nmd_shutdown:
+ EXPECT_ZERO(nmdShutdown(tlhCluster));
+ nmdFree(tlhCluster);
+done_rmdir:
+ if (mntTmp[0]) {
+ rmdir(mntTmp);
+ }
+done:
+ if (ret == EXIT_SUCCESS) {
+ fprintf(stderr, "FUSE_TEST: SUCCESS.\n");
+ } else {
+ fprintf(stderr, "FUSE_TEST: FAILURE!\n");
+ }
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/posix_util.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/posix_util.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/posix_util.c
new file mode 100644
index 0000000..59308a5
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/posix_util.c
@@ -0,0 +1,155 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "util/posix_util.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <limits.h>
+
+static pthread_mutex_t gTempdirLock = PTHREAD_MUTEX_INITIALIZER;
+
+static int gTempdirNonce = 0;
+
+int recursiveDeleteContents(const char *path)
+{
+ int ret;
+ DIR *dp;
+ struct dirent *de;
+ char tmp[PATH_MAX];
+
+ dp = opendir(path);
+ if (!dp) {
+ ret = -errno;
+ fprintf(stderr, "recursiveDelete(%s) failed with error %d\n", path, ret);
+ return ret;
+ }
+ while (1) {
+ de = readdir(dp);
+ if (!de) {
+ ret = 0;
+ break;
+ }
+ if ((de->d_name[0] == '.') && (de->d_name[1] == '\0'))
+ continue;
+ if ((de->d_name[0] == '.') && (de->d_name[1] == '.') &&
+ (de->d_name[2] == '\0'))
+ continue;
+ snprintf(tmp, sizeof(tmp), "%s/%s", path, de->d_name);
+ ret = recursiveDelete(tmp);
+ if (ret)
+ break;
+ }
+ if (closedir(dp)) {
+ ret = -errno;
+ fprintf(stderr, "recursiveDelete(%s): closedir failed with "
+ "error %d\n", path, ret);
+ return ret;
+ }
+ return ret;
+}
+
+/*
+ * Simple recursive delete implementation.
+ * It could be optimized, but there is no need at the moment.
+ * TODO: use fstat, etc.
+ */
+int recursiveDelete(const char *path)
+{
+ int ret;
+ struct stat stBuf;
+
+ ret = stat(path, &stBuf);
+ if (ret != 0) {
+ ret = -errno;
+ fprintf(stderr, "recursiveDelete(%s): stat failed with "
+ "error %d\n", path, ret);
+ return ret;
+ }
+ if (S_ISDIR(stBuf.st_mode)) {
+ ret = recursiveDeleteContents(path);
+ if (ret)
+ return ret;
+ ret = rmdir(path);
+ if (ret) {
+ ret = errno;
+ fprintf(stderr, "recursiveDelete(%s): rmdir failed with error %d\n",
+ path, ret);
+ return ret;
+ }
+ } else {
+ ret = unlink(path);
+ if (ret) {
+ ret = -errno;
+ fprintf(stderr, "recursiveDelete(%s): unlink failed with "
+ "error %d\n", path, ret);
+ return ret;
+ }
+ }
+ return 0;
+}
+
+int createTempDir(char *tempDir, int nameMax, int mode)
+{
+ char tmp[PATH_MAX];
+ int pid, nonce;
+ const char *base = getenv("TMPDIR");
+ if (!base)
+ base = "/tmp";
+ if (base[0] != '/') {
+ // canonicalize non-absolute TMPDIR
+ if (realpath(base, tmp) == NULL) {
+ return -errno;
+ }
+ base = tmp;
+ }
+ pid = getpid();
+ pthread_mutex_lock(&gTempdirLock);
+ nonce = gTempdirNonce++;
+ pthread_mutex_unlock(&gTempdirLock);
+ snprintf(tempDir, nameMax, "%s/temp.%08d.%08d", base, pid, nonce);
+ if (mkdir(tempDir, mode) == -1) {
+ int ret = errno;
+ return -ret;
+ }
+ return 0;
+}
+
+void sleepNoSig(int sec)
+{
+ int ret;
+ struct timespec req, rem;
+
+ rem.tv_sec = sec;
+ rem.tv_nsec = 0;
+ do {
+ req = rem;
+ ret = nanosleep(&req, &rem);
+ } while ((ret == -1) && (errno == EINTR));
+ if (ret == -1) {
+ ret = errno;
+ fprintf(stderr, "nanosleep error %d (%s)\n", ret, strerror(ret));
+ }
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/posix_util.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/posix_util.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/posix_util.h
new file mode 100644
index 0000000..c184c26
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/posix_util.h
@@ -0,0 +1,58 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __POSIX_UTIL_H__
+#define __POSIX_UTIL_H__
+
+/**
+ * Recursively delete the contents of a directory
+ *
+ * @param path directory whose contents we should delete
+ *
+ * @return 0 on success; error code otherwise
+ */
+int recursiveDeleteContents(const char *path);
+
+/**
+ * Recursively delete a local path, using unlink or rmdir as appropriate.
+ *
+ * @param path path to delete
+ *
+ * @return 0 on success; error code otherwise
+ */
+int recursiveDelete(const char *path);
+
+/**
+ * Get a temporary directory
+ *
+ * @param tempDir (out param) path to the temporary directory
+ * @param nameMax Length of the tempDir buffer
+ * @param mode Mode to create with
+ *
+ * @return 0 on success; error code otherwise
+ */
+int createTempDir(char *tempDir, int nameMax, int mode);
+
+/**
+ * Sleep without using signals
+ *
+ * @param sec Number of seconds to sleep
+ */
+void sleepNoSig(int sec);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/tree.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/tree.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/tree.h
new file mode 100644
index 0000000..ac78ee3
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/util/tree.h
@@ -0,0 +1,765 @@
+/* $NetBSD: tree.h,v 1.8 2004/03/28 19:38:30 provos Exp $ */
+/* $OpenBSD: tree.h,v 1.7 2002/10/17 21:51:54 art Exp $ */
+/* $FreeBSD: src/sys/sys/tree.h,v 1.9.4.1 2011/09/23 00:51:37 kensmith Exp $ */
+
+/*-
+ * Copyright 2002 Niels Provos <pr...@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _SYS_TREE_H_
+#define _SYS_TREE_H_
+
+#include <sys/cdefs.h>
+
+/*
+ * This file defines data structures for different types of trees:
+ * splay trees and red-black trees.
+ *
+ * A splay tree is a self-organizing data structure. Every operation
+ * on the tree causes a splay to happen. The splay moves the requested
+ * node to the root of the tree and partly rebalances it.
+ *
+ * This has the benefit that request locality causes faster lookups as
+ * the requested nodes move to the top of the tree. On the other hand,
+ * every lookup causes memory writes.
+ *
+ * The Balance Theorem bounds the total access time for m operations
+ * and n inserts on an initially empty tree as O((m + n)lg n). The
+ * amortized cost for a sequence of m accesses to a splay tree is O(lg n);
+ *
+ * A red-black tree is a binary search tree with the node color as an
+ * extra attribute. It fulfills a set of conditions:
+ * - every search path from the root to a leaf consists of the
+ * same number of black nodes,
+ * - each red node (except for the root) has a black parent,
+ * - each leaf node is black.
+ *
+ * Every operation on a red-black tree is bounded as O(lg n).
+ * The maximum height of a red-black tree is 2lg (n+1).
+ */
+
+#define SPLAY_HEAD(name, type) \
+struct name { \
+ struct type *sph_root; /* root of the tree */ \
+}
+
+#define SPLAY_INITIALIZER(root) \
+ { NULL }
+
+#define SPLAY_INIT(root) do { \
+ (root)->sph_root = NULL; \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_ENTRY(type) \
+struct { \
+ struct type *spe_left; /* left element */ \
+ struct type *spe_right; /* right element */ \
+}
+
+#define SPLAY_LEFT(elm, field) (elm)->field.spe_left
+#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right
+#define SPLAY_ROOT(head) (head)->sph_root
+#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL)
+
+/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
+#define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \
+ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \
+ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
+ (head)->sph_root = tmp; \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_ROTATE_LEFT(head, tmp, field) do { \
+ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \
+ SPLAY_LEFT(tmp, field) = (head)->sph_root; \
+ (head)->sph_root = tmp; \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_LINKLEFT(head, tmp, field) do { \
+ SPLAY_LEFT(tmp, field) = (head)->sph_root; \
+ tmp = (head)->sph_root; \
+ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_LINKRIGHT(head, tmp, field) do { \
+ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
+ tmp = (head)->sph_root; \
+ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_ASSEMBLE(head, node, left, right, field) do { \
+ SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \
+ SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\
+ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \
+ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \
+} while (/*CONSTCOND*/ 0)
+
+/* Generates prototypes and inline functions */
+
+#define SPLAY_PROTOTYPE(name, type, field, cmp) \
+void name##_SPLAY(struct name *, struct type *); \
+void name##_SPLAY_MINMAX(struct name *, int); \
+struct type *name##_SPLAY_INSERT(struct name *, struct type *); \
+struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \
+ \
+/* Finds the node with the same key as elm */ \
+static __inline struct type * \
+name##_SPLAY_FIND(struct name *head, struct type *elm) \
+{ \
+ if (SPLAY_EMPTY(head)) \
+ return(NULL); \
+ name##_SPLAY(head, elm); \
+ if ((cmp)(elm, (head)->sph_root) == 0) \
+ return (head->sph_root); \
+ return (NULL); \
+} \
+ \
+static __inline struct type * \
+name##_SPLAY_NEXT(struct name *head, struct type *elm) \
+{ \
+ name##_SPLAY(head, elm); \
+ if (SPLAY_RIGHT(elm, field) != NULL) { \
+ elm = SPLAY_RIGHT(elm, field); \
+ while (SPLAY_LEFT(elm, field) != NULL) { \
+ elm = SPLAY_LEFT(elm, field); \
+ } \
+ } else \
+ elm = NULL; \
+ return (elm); \
+} \
+ \
+static __inline struct type * \
+name##_SPLAY_MIN_MAX(struct name *head, int val) \
+{ \
+ name##_SPLAY_MINMAX(head, val); \
+ return (SPLAY_ROOT(head)); \
+}
+
+/* Main splay operation.
+ * Moves node close to the key of elm to top
+ */
+#define SPLAY_GENERATE(name, type, field, cmp) \
+struct type * \
+name##_SPLAY_INSERT(struct name *head, struct type *elm) \
+{ \
+ if (SPLAY_EMPTY(head)) { \
+ SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \
+ } else { \
+ int __comp; \
+ name##_SPLAY(head, elm); \
+ __comp = (cmp)(elm, (head)->sph_root); \
+ if(__comp < 0) { \
+ SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\
+ SPLAY_RIGHT(elm, field) = (head)->sph_root; \
+ SPLAY_LEFT((head)->sph_root, field) = NULL; \
+ } else if (__comp > 0) { \
+ SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\
+ SPLAY_LEFT(elm, field) = (head)->sph_root; \
+ SPLAY_RIGHT((head)->sph_root, field) = NULL; \
+ } else \
+ return ((head)->sph_root); \
+ } \
+ (head)->sph_root = (elm); \
+ return (NULL); \
+} \
+ \
+struct type * \
+name##_SPLAY_REMOVE(struct name *head, struct type *elm) \
+{ \
+ struct type *__tmp; \
+ if (SPLAY_EMPTY(head)) \
+ return (NULL); \
+ name##_SPLAY(head, elm); \
+ if ((cmp)(elm, (head)->sph_root) == 0) { \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \
+ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\
+ } else { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\
+ name##_SPLAY(head, elm); \
+ SPLAY_RIGHT((head)->sph_root, field) = __tmp; \
+ } \
+ return (elm); \
+ } \
+ return (NULL); \
+} \
+ \
+void \
+name##_SPLAY(struct name *head, struct type *elm) \
+{ \
+ struct type __node, *__left, *__right, *__tmp; \
+ int __comp; \
+\
+ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+ __left = __right = &__node; \
+\
+ while ((__comp = (cmp)(elm, (head)->sph_root)) != 0) { \
+ if (__comp < 0) { \
+ __tmp = SPLAY_LEFT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if ((cmp)(elm, __tmp) < 0){ \
+ SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+ break; \
+ } \
+ SPLAY_LINKLEFT(head, __right, field); \
+ } else if (__comp > 0) { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if ((cmp)(elm, __tmp) > 0){ \
+ SPLAY_ROTATE_LEFT(head, __tmp, field); \
+ if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+ break; \
+ } \
+ SPLAY_LINKRIGHT(head, __left, field); \
+ } \
+ } \
+ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
+} \
+ \
+/* Splay with either the minimum or the maximum element \
+ * Used to find minimum or maximum element in tree. \
+ */ \
+void name##_SPLAY_MINMAX(struct name *head, int __comp) \
+{ \
+ struct type __node, *__left, *__right, *__tmp; \
+\
+ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+ __left = __right = &__node; \
+\
+ while (1) { \
+ if (__comp < 0) { \
+ __tmp = SPLAY_LEFT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if (__comp < 0){ \
+ SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+ break; \
+ } \
+ SPLAY_LINKLEFT(head, __right, field); \
+ } else if (__comp > 0) { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if (__comp > 0) { \
+ SPLAY_ROTATE_LEFT(head, __tmp, field); \
+ if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+ break; \
+ } \
+ SPLAY_LINKRIGHT(head, __left, field); \
+ } \
+ } \
+ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
+}
+
+#define SPLAY_NEGINF -1
+#define SPLAY_INF 1
+
+#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y)
+#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y)
+#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y)
+#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y)
+#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \
+ : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
+#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \
+ : name##_SPLAY_MIN_MAX(x, SPLAY_INF))
+
+#define SPLAY_FOREACH(x, name, head) \
+ for ((x) = SPLAY_MIN(name, head); \
+ (x) != NULL; \
+ (x) = SPLAY_NEXT(name, head, x))
+
+/* Macros that define a red-black tree */
+#define RB_HEAD(name, type) \
+struct name { \
+ struct type *rbh_root; /* root of the tree */ \
+}
+
+#define RB_INITIALIZER(root) \
+ { NULL }
+
+#define RB_INIT(root) do { \
+ (root)->rbh_root = NULL; \
+} while (/*CONSTCOND*/ 0)
+
+#define RB_BLACK 0
+#define RB_RED 1
+#define RB_ENTRY(type) \
+struct { \
+ struct type *rbe_left; /* left element */ \
+ struct type *rbe_right; /* right element */ \
+ struct type *rbe_parent; /* parent element */ \
+ int rbe_color; /* node color */ \
+}
+
+#define RB_LEFT(elm, field) (elm)->field.rbe_left
+#define RB_RIGHT(elm, field) (elm)->field.rbe_right
+#define RB_PARENT(elm, field) (elm)->field.rbe_parent
+#define RB_COLOR(elm, field) (elm)->field.rbe_color
+#define RB_ROOT(head) (head)->rbh_root
+#define RB_EMPTY(head) (RB_ROOT(head) == NULL)
+
+#define RB_SET(elm, parent, field) do { \
+ RB_PARENT(elm, field) = parent; \
+ RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \
+ RB_COLOR(elm, field) = RB_RED; \
+} while (/*CONSTCOND*/ 0)
+
+#define RB_SET_BLACKRED(black, red, field) do { \
+ RB_COLOR(black, field) = RB_BLACK; \
+ RB_COLOR(red, field) = RB_RED; \
+} while (/*CONSTCOND*/ 0)
+
+#ifndef RB_AUGMENT
+#define RB_AUGMENT(x) do {} while (0)
+#endif
+
+#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \
+ (tmp) = RB_RIGHT(elm, field); \
+ if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field)) != NULL) { \
+ RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \
+ } \
+ RB_AUGMENT(elm); \
+ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
+ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
+ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
+ else \
+ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+ } else \
+ (head)->rbh_root = (tmp); \
+ RB_LEFT(tmp, field) = (elm); \
+ RB_PARENT(elm, field) = (tmp); \
+ RB_AUGMENT(tmp); \
+ if ((RB_PARENT(tmp, field))) \
+ RB_AUGMENT(RB_PARENT(tmp, field)); \
+} while (/*CONSTCOND*/ 0)
+
+#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \
+ (tmp) = RB_LEFT(elm, field); \
+ if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field)) != NULL) { \
+ RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \
+ } \
+ RB_AUGMENT(elm); \
+ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
+ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
+ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
+ else \
+ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+ } else \
+ (head)->rbh_root = (tmp); \
+ RB_RIGHT(tmp, field) = (elm); \
+ RB_PARENT(elm, field) = (tmp); \
+ RB_AUGMENT(tmp); \
+ if ((RB_PARENT(tmp, field))) \
+ RB_AUGMENT(RB_PARENT(tmp, field)); \
+} while (/*CONSTCOND*/ 0)
+
+/* Generates prototypes and inline functions */
+#define RB_PROTOTYPE(name, type, field, cmp) \
+ RB_PROTOTYPE_INTERNAL(name, type, field, cmp,)
+#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \
+ RB_PROTOTYPE_INTERNAL(name, type, field, cmp, __unused static)
+#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \
+attr void name##_RB_INSERT_COLOR(struct name *, struct type *); \
+attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
+attr struct type *name##_RB_REMOVE(struct name *, struct type *); \
+attr struct type *name##_RB_INSERT(struct name *, struct type *); \
+attr struct type *name##_RB_FIND(struct name *, struct type *); \
+attr struct type *name##_RB_NFIND(struct name *, struct type *); \
+attr struct type *name##_RB_NEXT(struct type *); \
+attr struct type *name##_RB_PREV(struct type *); \
+attr struct type *name##_RB_MINMAX(struct name *, int); \
+ \
+
+/* Main rb operation.
+ * Moves node close to the key of elm to top
+ */
+#define RB_GENERATE(name, type, field, cmp) \
+ RB_GENERATE_INTERNAL(name, type, field, cmp,)
+#define RB_GENERATE_STATIC(name, type, field, cmp) \
+ RB_GENERATE_INTERNAL(name, type, field, cmp, __unused static)
+#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \
+attr void \
+name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \
+{ \
+ struct type *parent, *gparent, *tmp; \
+ while ((parent = RB_PARENT(elm, field)) != NULL && \
+ RB_COLOR(parent, field) == RB_RED) { \
+ gparent = RB_PARENT(parent, field); \
+ if (parent == RB_LEFT(gparent, field)) { \
+ tmp = RB_RIGHT(gparent, field); \
+ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
+ RB_COLOR(tmp, field) = RB_BLACK; \
+ RB_SET_BLACKRED(parent, gparent, field);\
+ elm = gparent; \
+ continue; \
+ } \
+ if (RB_RIGHT(parent, field) == elm) { \
+ RB_ROTATE_LEFT(head, parent, tmp, field);\
+ tmp = parent; \
+ parent = elm; \
+ elm = tmp; \
+ } \
+ RB_SET_BLACKRED(parent, gparent, field); \
+ RB_ROTATE_RIGHT(head, gparent, tmp, field); \
+ } else { \
+ tmp = RB_LEFT(gparent, field); \
+ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
+ RB_COLOR(tmp, field) = RB_BLACK; \
+ RB_SET_BLACKRED(parent, gparent, field);\
+ elm = gparent; \
+ continue; \
+ } \
+ if (RB_LEFT(parent, field) == elm) { \
+ RB_ROTATE_RIGHT(head, parent, tmp, field);\
+ tmp = parent; \
+ parent = elm; \
+ elm = tmp; \
+ } \
+ RB_SET_BLACKRED(parent, gparent, field); \
+ RB_ROTATE_LEFT(head, gparent, tmp, field); \
+ } \
+ } \
+ RB_COLOR(head->rbh_root, field) = RB_BLACK; \
+} \
+ \
+attr void \
+name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \
+{ \
+ struct type *tmp; \
+ while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \
+ elm != RB_ROOT(head)) { \
+ if (RB_LEFT(parent, field) == elm) { \
+ tmp = RB_RIGHT(parent, field); \
+ if (RB_COLOR(tmp, field) == RB_RED) { \
+ RB_SET_BLACKRED(tmp, parent, field); \
+ RB_ROTATE_LEFT(head, parent, tmp, field);\
+ tmp = RB_RIGHT(parent, field); \
+ } \
+ if ((RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+ (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+ RB_COLOR(tmp, field) = RB_RED; \
+ elm = parent; \
+ parent = RB_PARENT(elm, field); \
+ } else { \
+ if (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\
+ struct type *oleft; \
+ if ((oleft = RB_LEFT(tmp, field)) \
+ != NULL) \
+ RB_COLOR(oleft, field) = RB_BLACK;\
+ RB_COLOR(tmp, field) = RB_RED; \
+ RB_ROTATE_RIGHT(head, tmp, oleft, field);\
+ tmp = RB_RIGHT(parent, field); \
+ } \
+ RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+ RB_COLOR(parent, field) = RB_BLACK; \
+ if (RB_RIGHT(tmp, field)) \
+ RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\
+ RB_ROTATE_LEFT(head, parent, tmp, field);\
+ elm = RB_ROOT(head); \
+ break; \
+ } \
+ } else { \
+ tmp = RB_LEFT(parent, field); \
+ if (RB_COLOR(tmp, field) == RB_RED) { \
+ RB_SET_BLACKRED(tmp, parent, field); \
+ RB_ROTATE_RIGHT(head, parent, tmp, field);\
+ tmp = RB_LEFT(parent, field); \
+ } \
+ if ((RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+ (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+ RB_COLOR(tmp, field) = RB_RED; \
+ elm = parent; \
+ parent = RB_PARENT(elm, field); \
+ } else { \
+ if (RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\
+ struct type *oright; \
+ if ((oright = RB_RIGHT(tmp, field)) \
+ != NULL) \
+ RB_COLOR(oright, field) = RB_BLACK;\
+ RB_COLOR(tmp, field) = RB_RED; \
+ RB_ROTATE_LEFT(head, tmp, oright, field);\
+ tmp = RB_LEFT(parent, field); \
+ } \
+ RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+ RB_COLOR(parent, field) = RB_BLACK; \
+ if (RB_LEFT(tmp, field)) \
+ RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\
+ RB_ROTATE_RIGHT(head, parent, tmp, field);\
+ elm = RB_ROOT(head); \
+ break; \
+ } \
+ } \
+ } \
+ if (elm) \
+ RB_COLOR(elm, field) = RB_BLACK; \
+} \
+ \
+attr struct type * \
+name##_RB_REMOVE(struct name *head, struct type *elm) \
+{ \
+ struct type *child, *parent, *old = elm; \
+ int color; \
+ if (RB_LEFT(elm, field) == NULL) \
+ child = RB_RIGHT(elm, field); \
+ else if (RB_RIGHT(elm, field) == NULL) \
+ child = RB_LEFT(elm, field); \
+ else { \
+ struct type *left; \
+ elm = RB_RIGHT(elm, field); \
+ while ((left = RB_LEFT(elm, field)) != NULL) \
+ elm = left; \
+ child = RB_RIGHT(elm, field); \
+ parent = RB_PARENT(elm, field); \
+ color = RB_COLOR(elm, field); \
+ if (child) \
+ RB_PARENT(child, field) = parent; \
+ if (parent) { \
+ if (RB_LEFT(parent, field) == elm) \
+ RB_LEFT(parent, field) = child; \
+ else \
+ RB_RIGHT(parent, field) = child; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = child; \
+ if (RB_PARENT(elm, field) == old) \
+ parent = elm; \
+ (elm)->field = (old)->field; \
+ if (RB_PARENT(old, field)) { \
+ if (RB_LEFT(RB_PARENT(old, field), field) == old)\
+ RB_LEFT(RB_PARENT(old, field), field) = elm;\
+ else \
+ RB_RIGHT(RB_PARENT(old, field), field) = elm;\
+ RB_AUGMENT(RB_PARENT(old, field)); \
+ } else \
+ RB_ROOT(head) = elm; \
+ RB_PARENT(RB_LEFT(old, field), field) = elm; \
+ if (RB_RIGHT(old, field)) \
+ RB_PARENT(RB_RIGHT(old, field), field) = elm; \
+ if (parent) { \
+ left = parent; \
+ do { \
+ RB_AUGMENT(left); \
+ } while ((left = RB_PARENT(left, field)) != NULL); \
+ } \
+ goto color; \
+ } \
+ parent = RB_PARENT(elm, field); \
+ color = RB_COLOR(elm, field); \
+ if (child) \
+ RB_PARENT(child, field) = parent; \
+ if (parent) { \
+ if (RB_LEFT(parent, field) == elm) \
+ RB_LEFT(parent, field) = child; \
+ else \
+ RB_RIGHT(parent, field) = child; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = child; \
+color: \
+ if (color == RB_BLACK) \
+ name##_RB_REMOVE_COLOR(head, parent, child); \
+ return (old); \
+} \
+ \
+/* Inserts a node into the RB tree */ \
+attr struct type * \
+name##_RB_INSERT(struct name *head, struct type *elm) \
+{ \
+ struct type *tmp; \
+ struct type *parent = NULL; \
+ int comp = 0; \
+ tmp = RB_ROOT(head); \
+ while (tmp) { \
+ parent = tmp; \
+ comp = (cmp)(elm, parent); \
+ if (comp < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else if (comp > 0) \
+ tmp = RB_RIGHT(tmp, field); \
+ else \
+ return (tmp); \
+ } \
+ RB_SET(elm, parent, field); \
+ if (parent != NULL) { \
+ if (comp < 0) \
+ RB_LEFT(parent, field) = elm; \
+ else \
+ RB_RIGHT(parent, field) = elm; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = elm; \
+ name##_RB_INSERT_COLOR(head, elm); \
+ return (NULL); \
+} \
+ \
+/* Finds the node with the same key as elm */ \
+attr struct type * \
+name##_RB_FIND(struct name *head, struct type *elm) \
+{ \
+ struct type *tmp = RB_ROOT(head); \
+ int comp; \
+ while (tmp) { \
+ comp = cmp(elm, tmp); \
+ if (comp < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else if (comp > 0) \
+ tmp = RB_RIGHT(tmp, field); \
+ else \
+ return (tmp); \
+ } \
+ return (NULL); \
+} \
+ \
+/* Finds the first node greater than or equal to the search key */ \
+attr struct type * \
+name##_RB_NFIND(struct name *head, struct type *elm) \
+{ \
+ struct type *tmp = RB_ROOT(head); \
+ struct type *res = NULL; \
+ int comp; \
+ while (tmp) { \
+ comp = cmp(elm, tmp); \
+ if (comp < 0) { \
+ res = tmp; \
+ tmp = RB_LEFT(tmp, field); \
+ } \
+ else if (comp > 0) \
+ tmp = RB_RIGHT(tmp, field); \
+ else \
+ return (tmp); \
+ } \
+ return (res); \
+} \
+ \
+/* ARGSUSED */ \
+attr struct type * \
+name##_RB_NEXT(struct type *elm) \
+{ \
+ if (RB_RIGHT(elm, field)) { \
+ elm = RB_RIGHT(elm, field); \
+ while (RB_LEFT(elm, field)) \
+ elm = RB_LEFT(elm, field); \
+ } else { \
+ if (RB_PARENT(elm, field) && \
+ (elm == RB_LEFT(RB_PARENT(elm, field), field))) \
+ elm = RB_PARENT(elm, field); \
+ else { \
+ while (RB_PARENT(elm, field) && \
+ (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\
+ elm = RB_PARENT(elm, field); \
+ elm = RB_PARENT(elm, field); \
+ } \
+ } \
+ return (elm); \
+} \
+ \
+/* ARGSUSED */ \
+attr struct type * \
+name##_RB_PREV(struct type *elm) \
+{ \
+ if (RB_LEFT(elm, field)) { \
+ elm = RB_LEFT(elm, field); \
+ while (RB_RIGHT(elm, field)) \
+ elm = RB_RIGHT(elm, field); \
+ } else { \
+ if (RB_PARENT(elm, field) && \
+ (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \
+ elm = RB_PARENT(elm, field); \
+ else { \
+ while (RB_PARENT(elm, field) && \
+ (elm == RB_LEFT(RB_PARENT(elm, field), field)))\
+ elm = RB_PARENT(elm, field); \
+ elm = RB_PARENT(elm, field); \
+ } \
+ } \
+ return (elm); \
+} \
+ \
+attr struct type * \
+name##_RB_MINMAX(struct name *head, int val) \
+{ \
+ struct type *tmp = RB_ROOT(head); \
+ struct type *parent = NULL; \
+ while (tmp) { \
+ parent = tmp; \
+ if (val < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else \
+ tmp = RB_RIGHT(tmp, field); \
+ } \
+ return (parent); \
+}
+
+#define RB_NEGINF -1
+#define RB_INF 1
+
+#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y)
+#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y)
+#define RB_FIND(name, x, y) name##_RB_FIND(x, y)
+#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y)
+#define RB_NEXT(name, x, y) name##_RB_NEXT(y)
+#define RB_PREV(name, x, y) name##_RB_PREV(y)
+#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF)
+#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF)
+
+#define RB_FOREACH(x, name, head) \
+ for ((x) = RB_MIN(name, head); \
+ (x) != NULL; \
+ (x) = name##_RB_NEXT(x))
+
+#define RB_FOREACH_FROM(x, name, y) \
+ for ((x) = (y); \
+ ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \
+ (x) = (y))
+
+#define RB_FOREACH_SAFE(x, name, head, y) \
+ for ((x) = RB_MIN(name, head); \
+ ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \
+ (x) = (y))
+
+#define RB_FOREACH_REVERSE(x, name, head) \
+ for ((x) = RB_MAX(name, head); \
+ (x) != NULL; \
+ (x) = name##_RB_PREV(x))
+
+#define RB_FOREACH_REVERSE_FROM(x, name, y) \
+ for ((x) = (y); \
+ ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \
+ (x) = (y))
+
+#define RB_FOREACH_REVERSE_SAFE(x, name, head, y) \
+ for ((x) = RB_MAX(name, head); \
+ ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \
+ (x) = (y))
+
+#endif /* _SYS_TREE_H_ */
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/CMakeLists.txt b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/CMakeLists.txt
new file mode 100644
index 0000000..772a864
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfs/CMakeLists.txt
@@ -0,0 +1,141 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+#
+add_definitions(-DLIBHDFS_DLL_EXPORT)
+
+include_directories(
+ ${GENERATED_JAVAH}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${JNI_INCLUDE_DIRS}
+ main/native
+ main/native/libhdfs
+ ${OS_DIR}
+)
+
+hadoop_add_dual_library(hdfs
+ exception.c
+ jni_helper.c
+ hdfs.c
+ common/htable.c
+ ${OS_DIR}/mutexes.c
+ ${OS_DIR}/thread_local_storage.c
+)
+if(NEED_LINK_DL)
+ set(LIB_DL dl)
+endif()
+
+hadoop_target_link_dual_libraries(hdfs
+ ${JAVA_JVM_LIBRARY}
+ ${LIB_DL}
+ ${OS_LINK_LIBRARIES}
+)
+
+hadoop_dual_output_directory(hdfs ${OUT_DIR})
+set(LIBHDFS_VERSION "0.0.0")
+set_target_properties(hdfs PROPERTIES
+ SOVERSION ${LIBHDFS_VERSION})
+
+add_executable(test_libhdfs_ops
+ test/test_libhdfs_ops.c
+)
+target_link_libraries(test_libhdfs_ops
+ hdfs_static
+ ${JAVA_JVM_LIBRARY}
+)
+
+add_executable(test_libhdfs_read
+ test/test_libhdfs_read.c
+)
+target_link_libraries(test_libhdfs_read
+ hdfs_static
+ ${JAVA_JVM_LIBRARY}
+)
+
+add_executable(test_libhdfs_write
+ test/test_libhdfs_write.c
+)
+target_link_libraries(test_libhdfs_write
+ hdfs_static
+ ${JAVA_JVM_LIBRARY}
+)
+
+add_library(native_mini_dfs
+ native_mini_dfs.c
+ common/htable.c
+ exception.c
+ jni_helper.c
+ ${OS_DIR}/mutexes.c
+ ${OS_DIR}/thread_local_storage.c
+)
+target_link_libraries(native_mini_dfs
+ ${JAVA_JVM_LIBRARY}
+ ${LIB_DL}
+ ${OS_LINK_LIBRARIES}
+)
+
+add_executable(test_native_mini_dfs
+ test_native_mini_dfs.c
+)
+target_link_libraries(test_native_mini_dfs
+ native_mini_dfs
+)
+
+add_executable(test_libhdfs_threaded
+ expect.c
+ test_libhdfs_threaded.c
+ ${OS_DIR}/thread.c
+)
+target_link_libraries(test_libhdfs_threaded
+ hdfs_static
+ native_mini_dfs
+ ${OS_LINK_LIBRARIES}
+)
+
+add_executable(test_libhdfs_zerocopy
+ expect.c
+ test/test_libhdfs_zerocopy.c
+)
+target_link_libraries(test_libhdfs_zerocopy
+ hdfs_static
+ native_mini_dfs
+ ${OS_LINK_LIBRARIES}
+)
+
+add_executable(test_htable
+ common/htable.c
+ test/test_htable.c
+)
+target_link_libraries(test_htable
+ ${OS_LINK_LIBRARIES}
+)
+
+# Skip vecsum on Windows. This could be made to work in the future by
+# introducing an abstraction layer over the sys/mman.h functions.
+if(NOT WIN32)
+ add_executable(test_libhdfs_vecsum test/vecsum.c)
+ if(CMAKE_SYSTEM_NAME MATCHES "Darwin")
+ target_link_libraries(test_libhdfs_vecsum
+ hdfs
+ pthread)
+ else()
+ target_link_libraries(test_libhdfs_vecsum
+ hdfs
+ pthread
+ rt)
+ endif()
+endif()
[05/35] hadoop git commit: HDFS-9196. Fix TestWebHdfsContentLength.
Contributed by Masatake Iwasaki.
Posted by ji...@apache.org.
HDFS-9196. Fix TestWebHdfsContentLength. Contributed by Masatake Iwasaki.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/239d119c
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/239d119c
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/239d119c
Branch: refs/heads/HDFS-8966
Commit: 239d119c6707e58c9a5e0099c6d65fe956e95140
Parents: 8e53311
Author: Jing Zhao <ji...@apache.org>
Authored: Tue Oct 6 23:54:49 2015 -0700
Committer: Jing Zhao <ji...@apache.org>
Committed: Tue Oct 6 23:54:49 2015 -0700
----------------------------------------------------------------------
.../main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java | 2 +-
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 2 ++
2 files changed, 3 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/239d119c/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
index 16d41a7..8bdf3ba 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
@@ -212,7 +212,7 @@ public class WebHdfsFileSystem extends FileSystem
failoverSleepMaxMillis);
}
- this.workingDir = makeQualified(getHomeDirectory());
+ this.workingDir = makeQualified(new Path(getHomeDirectoryString(ugi)));
this.canRefreshDelegationToken = UserGroupInformation.isSecurityEnabled();
this.disallowFallbackToInsecureCluster = !conf.getBoolean(
CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY,
http://git-wip-us.apache.org/repos/asf/hadoop/blob/239d119c/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 93d3ee7..754ae7a 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1967,6 +1967,8 @@ Release 2.8.0 - UNRELEASED
HDFS-7899. Improve EOF error message (Jagadesh Kiran N via vinayakumarb)
+ HDFS-9196. Fix TestWebHdfsContentLength. (Masatake Iwasaki via jing9)
+
Release 2.7.2 - UNRELEASED
INCOMPATIBLE CHANGES
[28/35] hadoop git commit: HDFS-9176. Fix
TestDirectoryScanner#testThrottling often fails. (Daniel Templeton via lei)
Posted by ji...@apache.org.
HDFS-9176. Fix TestDirectoryScanner#testThrottling often fails. (Daniel Templeton via lei)
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/6dd47d75
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/6dd47d75
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/6dd47d75
Branch: refs/heads/HDFS-8966
Commit: 6dd47d754cb11297c8710a5c318c034abea7a836
Parents: 7fbf69b
Author: Lei Xu <le...@apache.org>
Authored: Wed Oct 7 14:33:43 2015 -0700
Committer: Lei Xu <le...@apache.org>
Committed: Wed Oct 7 14:33:43 2015 -0700
----------------------------------------------------------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +++
.../hdfs/server/datanode/TestDirectoryScanner.java | 17 ++++++++++++-----
2 files changed, 15 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/6dd47d75/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 33a78f0..c1343e4 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1974,6 +1974,9 @@ Release 2.8.0 - UNRELEASED
HDFS-9159. [OIV] : return value of the command is not correct if invalid
value specified in "-p (processor)" option (nijel via vinayakumarb)
+ HDFS-9176. Fix TestDirectoryScanner#testThrottling often fails.
+ (Daniel Templeton via lei)
+
Release 2.7.2 - UNRELEASED
INCOMPATIBLE CHANGES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/6dd47d75/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDirectoryScanner.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDirectoryScanner.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDirectoryScanner.java
index 72c4497..250e07d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDirectoryScanner.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDirectoryScanner.java
@@ -665,17 +665,24 @@ public class TestDirectoryScanner {
interruptor.schedule(new Runnable() {
@Override
public void run() {
- scanner.shutdown();
nowMs.set(Time.monotonicNow());
+ scanner.shutdown();
}
}, 2L, TimeUnit.SECONDS);
scanner.reconcile();
assertFalse(scanner.getRunStatus());
- LOG.info("Scanner took " + (Time.monotonicNow() - nowMs.get())
- + "ms to shutdown");
- assertTrue("Scanner took too long to shutdown",
- Time.monotonicNow() - nowMs.get() < 1000L);
+
+ long finalMs = nowMs.get();
+
+ // If the scan didn't complete before the shutdown was run, check
+ // that the shutdown was timely
+ if (finalMs > 0) {
+ LOG.info("Scanner took " + (Time.monotonicNow() - finalMs)
+ + "ms to shutdown");
+ assertTrue("Scanner took too long to shutdown",
+ Time.monotonicNow() - finalMs < 1000L);
+ }
ratio =
(float)scanner.timeWaitingMs.get() / scanner.timeRunningMs.get();
[08/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs.h
deleted file mode 100644
index c1515d7..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs.h
+++ /dev/null
@@ -1,939 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_HDFS_H
-#define LIBHDFS_HDFS_H
-
-#include <errno.h> /* for EINTERNAL, etc. */
-#include <fcntl.h> /* for O_RDONLY, O_WRONLY */
-#include <stdint.h> /* for uint64_t, etc. */
-#include <time.h> /* for time_t */
-
-/*
- * Support export of DLL symbols during libhdfs build, and import of DLL symbols
- * during client application build. A client application may optionally define
- * symbol LIBHDFS_DLL_IMPORT in its build. This is not strictly required, but
- * the compiler can produce more efficient code with it.
- */
-#ifdef WIN32
- #ifdef LIBHDFS_DLL_EXPORT
- #define LIBHDFS_EXTERNAL __declspec(dllexport)
- #elif LIBHDFS_DLL_IMPORT
- #define LIBHDFS_EXTERNAL __declspec(dllimport)
- #else
- #define LIBHDFS_EXTERNAL
- #endif
-#else
- #ifdef LIBHDFS_DLL_EXPORT
- #define LIBHDFS_EXTERNAL __attribute__((visibility("default")))
- #elif LIBHDFS_DLL_IMPORT
- #define LIBHDFS_EXTERNAL __attribute__((visibility("default")))
- #else
- #define LIBHDFS_EXTERNAL
- #endif
-#endif
-
-#ifndef O_RDONLY
-#define O_RDONLY 1
-#endif
-
-#ifndef O_WRONLY
-#define O_WRONLY 2
-#endif
-
-#ifndef EINTERNAL
-#define EINTERNAL 255
-#endif
-
-#define ELASTIC_BYTE_BUFFER_POOL_CLASS \
- "org/apache/hadoop/io/ElasticByteBufferPool"
-
-/** All APIs set errno to meaningful values */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
- /**
- * Some utility decls used in libhdfs.
- */
- struct hdfsBuilder;
- typedef int32_t tSize; /// size of data for read/write io ops
- typedef time_t tTime; /// time type in seconds
- typedef int64_t tOffset;/// offset within the file
- typedef uint16_t tPort; /// port
- typedef enum tObjectKind {
- kObjectKindFile = 'F',
- kObjectKindDirectory = 'D',
- } tObjectKind;
-
-
- /**
- * The C reflection of org.apache.org.hadoop.FileSystem .
- */
- struct hdfs_internal;
- typedef struct hdfs_internal* hdfsFS;
-
- struct hdfsFile_internal;
- typedef struct hdfsFile_internal* hdfsFile;
-
- struct hadoopRzOptions;
-
- struct hadoopRzBuffer;
-
- /**
- * Determine if a file is open for read.
- *
- * @param file The HDFS file
- * @return 1 if the file is open for read; 0 otherwise
- */
- LIBHDFS_EXTERNAL
- int hdfsFileIsOpenForRead(hdfsFile file);
-
- /**
- * Determine if a file is open for write.
- *
- * @param file The HDFS file
- * @return 1 if the file is open for write; 0 otherwise
- */
- LIBHDFS_EXTERNAL
- int hdfsFileIsOpenForWrite(hdfsFile file);
-
- struct hdfsReadStatistics {
- uint64_t totalBytesRead;
- uint64_t totalLocalBytesRead;
- uint64_t totalShortCircuitBytesRead;
- uint64_t totalZeroCopyBytesRead;
- };
-
- /**
- * Get read statistics about a file. This is only applicable to files
- * opened for reading.
- *
- * @param file The HDFS file
- * @param stats (out parameter) on a successful return, the read
- * statistics. Unchanged otherwise. You must free the
- * returned statistics with hdfsFileFreeReadStatistics.
- * @return 0 if the statistics were successfully returned,
- * -1 otherwise. On a failure, please check errno against
- * ENOTSUP. webhdfs, LocalFilesystem, and so forth may
- * not support read statistics.
- */
- LIBHDFS_EXTERNAL
- int hdfsFileGetReadStatistics(hdfsFile file,
- struct hdfsReadStatistics **stats);
-
- /**
- * @param stats HDFS read statistics for a file.
- *
- * @return the number of remote bytes read.
- */
- LIBHDFS_EXTERNAL
- int64_t hdfsReadStatisticsGetRemoteBytesRead(
- const struct hdfsReadStatistics *stats);
-
- /**
- * Clear the read statistics for a file.
- *
- * @param file The file to clear the read statistics of.
- *
- * @return 0 on success; the error code otherwise.
- * EINVAL: the file is not open for reading.
- * ENOTSUP: the file does not support clearing the read
- * statistics.
- * Errno will also be set to this code on failure.
- */
- LIBHDFS_EXTERNAL
- int hdfsFileClearReadStatistics(hdfsFile file);
-
- /**
- * Free some HDFS read statistics.
- *
- * @param stats The HDFS read statistics to free.
- */
- LIBHDFS_EXTERNAL
- void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats);
-
- /**
- * hdfsConnectAsUser - Connect to a hdfs file system as a specific user
- * Connect to the hdfs.
- * @param nn The NameNode. See hdfsBuilderSetNameNode for details.
- * @param port The port on which the server is listening.
- * @param user the user name (this is hadoop domain user). Or NULL is equivelant to hhdfsConnect(host, port)
- * @return Returns a handle to the filesystem or NULL on error.
- * @deprecated Use hdfsBuilderConnect instead.
- */
- LIBHDFS_EXTERNAL
- hdfsFS hdfsConnectAsUser(const char* nn, tPort port, const char *user);
-
- /**
- * hdfsConnect - Connect to a hdfs file system.
- * Connect to the hdfs.
- * @param nn The NameNode. See hdfsBuilderSetNameNode for details.
- * @param port The port on which the server is listening.
- * @return Returns a handle to the filesystem or NULL on error.
- * @deprecated Use hdfsBuilderConnect instead.
- */
- LIBHDFS_EXTERNAL
- hdfsFS hdfsConnect(const char* nn, tPort port);
-
- /**
- * hdfsConnect - Connect to an hdfs file system.
- *
- * Forces a new instance to be created
- *
- * @param nn The NameNode. See hdfsBuilderSetNameNode for details.
- * @param port The port on which the server is listening.
- * @param user The user name to use when connecting
- * @return Returns a handle to the filesystem or NULL on error.
- * @deprecated Use hdfsBuilderConnect instead.
- */
- LIBHDFS_EXTERNAL
- hdfsFS hdfsConnectAsUserNewInstance(const char* nn, tPort port, const char *user );
-
- /**
- * hdfsConnect - Connect to an hdfs file system.
- *
- * Forces a new instance to be created
- *
- * @param nn The NameNode. See hdfsBuilderSetNameNode for details.
- * @param port The port on which the server is listening.
- * @return Returns a handle to the filesystem or NULL on error.
- * @deprecated Use hdfsBuilderConnect instead.
- */
- LIBHDFS_EXTERNAL
- hdfsFS hdfsConnectNewInstance(const char* nn, tPort port);
-
- /**
- * Connect to HDFS using the parameters defined by the builder.
- *
- * The HDFS builder will be freed, whether or not the connection was
- * successful.
- *
- * Every successful call to hdfsBuilderConnect should be matched with a call
- * to hdfsDisconnect, when the hdfsFS is no longer needed.
- *
- * @param bld The HDFS builder
- * @return Returns a handle to the filesystem, or NULL on error.
- */
- LIBHDFS_EXTERNAL
- hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld);
-
- /**
- * Create an HDFS builder.
- *
- * @return The HDFS builder, or NULL on error.
- */
- LIBHDFS_EXTERNAL
- struct hdfsBuilder *hdfsNewBuilder(void);
-
- /**
- * Force the builder to always create a new instance of the FileSystem,
- * rather than possibly finding one in the cache.
- *
- * @param bld The HDFS builder
- */
- LIBHDFS_EXTERNAL
- void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld);
-
- /**
- * Set the HDFS NameNode to connect to.
- *
- * @param bld The HDFS builder
- * @param nn The NameNode to use.
- *
- * If the string given is 'default', the default NameNode
- * configuration will be used (from the XML configuration files)
- *
- * If NULL is given, a LocalFileSystem will be created.
- *
- * If the string starts with a protocol type such as file:// or
- * hdfs://, this protocol type will be used. If not, the
- * hdfs:// protocol type will be used.
- *
- * You may specify a NameNode port in the usual way by
- * passing a string of the format hdfs://<hostname>:<port>.
- * Alternately, you may set the port with
- * hdfsBuilderSetNameNodePort. However, you must not pass the
- * port in two different ways.
- */
- LIBHDFS_EXTERNAL
- void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn);
-
- /**
- * Set the port of the HDFS NameNode to connect to.
- *
- * @param bld The HDFS builder
- * @param port The port.
- */
- LIBHDFS_EXTERNAL
- void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port);
-
- /**
- * Set the username to use when connecting to the HDFS cluster.
- *
- * @param bld The HDFS builder
- * @param userName The user name. The string will be shallow-copied.
- */
- LIBHDFS_EXTERNAL
- void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName);
-
- /**
- * Set the path to the Kerberos ticket cache to use when connecting to
- * the HDFS cluster.
- *
- * @param bld The HDFS builder
- * @param kerbTicketCachePath The Kerberos ticket cache path. The string
- * will be shallow-copied.
- */
- LIBHDFS_EXTERNAL
- void hdfsBuilderSetKerbTicketCachePath(struct hdfsBuilder *bld,
- const char *kerbTicketCachePath);
-
- /**
- * Free an HDFS builder.
- *
- * It is normally not necessary to call this function since
- * hdfsBuilderConnect frees the builder.
- *
- * @param bld The HDFS builder
- */
- LIBHDFS_EXTERNAL
- void hdfsFreeBuilder(struct hdfsBuilder *bld);
-
- /**
- * Set a configuration string for an HdfsBuilder.
- *
- * @param key The key to set.
- * @param val The value, or NULL to set no value.
- * This will be shallow-copied. You are responsible for
- * ensuring that it remains valid until the builder is
- * freed.
- *
- * @return 0 on success; nonzero error code otherwise.
- */
- LIBHDFS_EXTERNAL
- int hdfsBuilderConfSetStr(struct hdfsBuilder *bld, const char *key,
- const char *val);
-
- /**
- * Get a configuration string.
- *
- * @param key The key to find
- * @param val (out param) The value. This will be set to NULL if the
- * key isn't found. You must free this string with
- * hdfsConfStrFree.
- *
- * @return 0 on success; nonzero error code otherwise.
- * Failure to find the key is not an error.
- */
- LIBHDFS_EXTERNAL
- int hdfsConfGetStr(const char *key, char **val);
-
- /**
- * Get a configuration integer.
- *
- * @param key The key to find
- * @param val (out param) The value. This will NOT be changed if the
- * key isn't found.
- *
- * @return 0 on success; nonzero error code otherwise.
- * Failure to find the key is not an error.
- */
- LIBHDFS_EXTERNAL
- int hdfsConfGetInt(const char *key, int32_t *val);
-
- /**
- * Free a configuration string found with hdfsConfGetStr.
- *
- * @param val A configuration string obtained from hdfsConfGetStr
- */
- LIBHDFS_EXTERNAL
- void hdfsConfStrFree(char *val);
-
- /**
- * hdfsDisconnect - Disconnect from the hdfs file system.
- * Disconnect from hdfs.
- * @param fs The configured filesystem handle.
- * @return Returns 0 on success, -1 on error.
- * Even if there is an error, the resources associated with the
- * hdfsFS will be freed.
- */
- LIBHDFS_EXTERNAL
- int hdfsDisconnect(hdfsFS fs);
-
-
- /**
- * hdfsOpenFile - Open a hdfs file in given mode.
- * @param fs The configured filesystem handle.
- * @param path The full path to the file.
- * @param flags - an | of bits/fcntl.h file flags - supported flags are O_RDONLY, O_WRONLY (meaning create or overwrite i.e., implies O_TRUNCAT),
- * O_WRONLY|O_APPEND. Other flags are generally ignored other than (O_RDWR || (O_EXCL & O_CREAT)) which return NULL and set errno equal ENOTSUP.
- * @param bufferSize Size of buffer for read/write - pass 0 if you want
- * to use the default configured values.
- * @param replication Block replication - pass 0 if you want to use
- * the default configured values.
- * @param blocksize Size of block - pass 0 if you want to use the
- * default configured values.
- * @return Returns the handle to the open file or NULL on error.
- */
- LIBHDFS_EXTERNAL
- hdfsFile hdfsOpenFile(hdfsFS fs, const char* path, int flags,
- int bufferSize, short replication, tSize blocksize);
-
- /**
- * hdfsTruncateFile - Truncate a hdfs file to given lenght.
- * @param fs The configured filesystem handle.
- * @param path The full path to the file.
- * @param newlength The size the file is to be truncated to
- * @return 1 if the file has been truncated to the desired newlength
- * and is immediately available to be reused for write operations
- * such as append.
- * 0 if a background process of adjusting the length of the last
- * block has been started, and clients should wait for it to
- * complete before proceeding with further file updates.
- * -1 on error.
- */
- int hdfsTruncateFile(hdfsFS fs, const char* path, tOffset newlength);
-
- /**
- * hdfsUnbufferFile - Reduce the buffering done on a file.
- *
- * @param file The file to unbuffer.
- * @return 0 on success
- * ENOTSUP if the file does not support unbuffering
- * Errno will also be set to this value.
- */
- LIBHDFS_EXTERNAL
- int hdfsUnbufferFile(hdfsFile file);
-
- /**
- * hdfsCloseFile - Close an open file.
- * @param fs The configured filesystem handle.
- * @param file The file handle.
- * @return Returns 0 on success, -1 on error.
- * On error, errno will be set appropriately.
- * If the hdfs file was valid, the memory associated with it will
- * be freed at the end of this call, even if there was an I/O
- * error.
- */
- LIBHDFS_EXTERNAL
- int hdfsCloseFile(hdfsFS fs, hdfsFile file);
-
-
- /**
- * hdfsExists - Checks if a given path exsits on the filesystem
- * @param fs The configured filesystem handle.
- * @param path The path to look for
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsExists(hdfsFS fs, const char *path);
-
-
- /**
- * hdfsSeek - Seek to given offset in file.
- * This works only for files opened in read-only mode.
- * @param fs The configured filesystem handle.
- * @param file The file handle.
- * @param desiredPos Offset into the file to seek into.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsSeek(hdfsFS fs, hdfsFile file, tOffset desiredPos);
-
-
- /**
- * hdfsTell - Get the current offset in the file, in bytes.
- * @param fs The configured filesystem handle.
- * @param file The file handle.
- * @return Current offset, -1 on error.
- */
- LIBHDFS_EXTERNAL
- tOffset hdfsTell(hdfsFS fs, hdfsFile file);
-
-
- /**
- * hdfsRead - Read data from an open file.
- * @param fs The configured filesystem handle.
- * @param file The file handle.
- * @param buffer The buffer to copy read bytes into.
- * @param length The length of the buffer.
- * @return On success, a positive number indicating how many bytes
- * were read.
- * On end-of-file, 0.
- * On error, -1. Errno will be set to the error code.
- * Just like the POSIX read function, hdfsRead will return -1
- * and set errno to EINTR if data is temporarily unavailable,
- * but we are not yet at the end of the file.
- */
- LIBHDFS_EXTERNAL
- tSize hdfsRead(hdfsFS fs, hdfsFile file, void* buffer, tSize length);
-
- /**
- * hdfsPread - Positional read of data from an open file.
- * @param fs The configured filesystem handle.
- * @param file The file handle.
- * @param position Position from which to read
- * @param buffer The buffer to copy read bytes into.
- * @param length The length of the buffer.
- * @return See hdfsRead
- */
- LIBHDFS_EXTERNAL
- tSize hdfsPread(hdfsFS fs, hdfsFile file, tOffset position,
- void* buffer, tSize length);
-
-
- /**
- * hdfsWrite - Write data into an open file.
- * @param fs The configured filesystem handle.
- * @param file The file handle.
- * @param buffer The data.
- * @param length The no. of bytes to write.
- * @return Returns the number of bytes written, -1 on error.
- */
- LIBHDFS_EXTERNAL
- tSize hdfsWrite(hdfsFS fs, hdfsFile file, const void* buffer,
- tSize length);
-
-
- /**
- * hdfsWrite - Flush the data.
- * @param fs The configured filesystem handle.
- * @param file The file handle.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsFlush(hdfsFS fs, hdfsFile file);
-
-
- /**
- * hdfsHFlush - Flush out the data in client's user buffer. After the
- * return of this call, new readers will see the data.
- * @param fs configured filesystem handle
- * @param file file handle
- * @return 0 on success, -1 on error and sets errno
- */
- LIBHDFS_EXTERNAL
- int hdfsHFlush(hdfsFS fs, hdfsFile file);
-
-
- /**
- * hdfsHSync - Similar to posix fsync, Flush out the data in client's
- * user buffer. all the way to the disk device (but the disk may have
- * it in its cache).
- * @param fs configured filesystem handle
- * @param file file handle
- * @return 0 on success, -1 on error and sets errno
- */
- LIBHDFS_EXTERNAL
- int hdfsHSync(hdfsFS fs, hdfsFile file);
-
-
- /**
- * hdfsAvailable - Number of bytes that can be read from this
- * input stream without blocking.
- * @param fs The configured filesystem handle.
- * @param file The file handle.
- * @return Returns available bytes; -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsAvailable(hdfsFS fs, hdfsFile file);
-
-
- /**
- * hdfsCopy - Copy file from one filesystem to another.
- * @param srcFS The handle to source filesystem.
- * @param src The path of source file.
- * @param dstFS The handle to destination filesystem.
- * @param dst The path of destination file.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsCopy(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst);
-
-
- /**
- * hdfsMove - Move file from one filesystem to another.
- * @param srcFS The handle to source filesystem.
- * @param src The path of source file.
- * @param dstFS The handle to destination filesystem.
- * @param dst The path of destination file.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsMove(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst);
-
-
- /**
- * hdfsDelete - Delete file.
- * @param fs The configured filesystem handle.
- * @param path The path of the file.
- * @param recursive if path is a directory and set to
- * non-zero, the directory is deleted else throws an exception. In
- * case of a file the recursive argument is irrelevant.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsDelete(hdfsFS fs, const char* path, int recursive);
-
- /**
- * hdfsRename - Rename file.
- * @param fs The configured filesystem handle.
- * @param oldPath The path of the source file.
- * @param newPath The path of the destination file.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath);
-
-
- /**
- * hdfsGetWorkingDirectory - Get the current working directory for
- * the given filesystem.
- * @param fs The configured filesystem handle.
- * @param buffer The user-buffer to copy path of cwd into.
- * @param bufferSize The length of user-buffer.
- * @return Returns buffer, NULL on error.
- */
- LIBHDFS_EXTERNAL
- char* hdfsGetWorkingDirectory(hdfsFS fs, char *buffer, size_t bufferSize);
-
-
- /**
- * hdfsSetWorkingDirectory - Set the working directory. All relative
- * paths will be resolved relative to it.
- * @param fs The configured filesystem handle.
- * @param path The path of the new 'cwd'.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsSetWorkingDirectory(hdfsFS fs, const char* path);
-
-
- /**
- * hdfsCreateDirectory - Make the given file and all non-existent
- * parents into directories.
- * @param fs The configured filesystem handle.
- * @param path The path of the directory.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsCreateDirectory(hdfsFS fs, const char* path);
-
-
- /**
- * hdfsSetReplication - Set the replication of the specified
- * file to the supplied value
- * @param fs The configured filesystem handle.
- * @param path The path of the file.
- * @return Returns 0 on success, -1 on error.
- */
- LIBHDFS_EXTERNAL
- int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication);
-
-
- /**
- * hdfsFileInfo - Information about a file/directory.
- */
- typedef struct {
- tObjectKind mKind; /* file or directory */
- char *mName; /* the name of the file */
- tTime mLastMod; /* the last modification time for the file in seconds */
- tOffset mSize; /* the size of the file in bytes */
- short mReplication; /* the count of replicas */
- tOffset mBlockSize; /* the block size for the file */
- char *mOwner; /* the owner of the file */
- char *mGroup; /* the group associated with the file */
- short mPermissions; /* the permissions associated with the file */
- tTime mLastAccess; /* the last access time for the file in seconds */
- } hdfsFileInfo;
-
-
- /**
- * hdfsListDirectory - Get list of files/directories for a given
- * directory-path. hdfsFreeFileInfo should be called to deallocate memory.
- * @param fs The configured filesystem handle.
- * @param path The path of the directory.
- * @param numEntries Set to the number of files/directories in path.
- * @return Returns a dynamically-allocated array of hdfsFileInfo
- * objects; NULL on error or empty directory.
- * errno is set to non-zero on error or zero on success.
- */
- LIBHDFS_EXTERNAL
- hdfsFileInfo *hdfsListDirectory(hdfsFS fs, const char* path,
- int *numEntries);
-
-
- /**
- * hdfsGetPathInfo - Get information about a path as a (dynamically
- * allocated) single hdfsFileInfo struct. hdfsFreeFileInfo should be
- * called when the pointer is no longer needed.
- * @param fs The configured filesystem handle.
- * @param path The path of the file.
- * @return Returns a dynamically-allocated hdfsFileInfo object;
- * NULL on error.
- */
- LIBHDFS_EXTERNAL
- hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path);
-
-
- /**
- * hdfsFreeFileInfo - Free up the hdfsFileInfo array (including fields)
- * @param hdfsFileInfo The array of dynamically-allocated hdfsFileInfo
- * objects.
- * @param numEntries The size of the array.
- */
- LIBHDFS_EXTERNAL
- void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries);
-
- /**
- * hdfsFileIsEncrypted: determine if a file is encrypted based on its
- * hdfsFileInfo.
- * @return -1 if there was an error (errno will be set), 0 if the file is
- * not encrypted, 1 if the file is encrypted.
- */
- LIBHDFS_EXTERNAL
- int hdfsFileIsEncrypted(hdfsFileInfo *hdfsFileInfo);
-
-
- /**
- * hdfsGetHosts - Get hostnames where a particular block (determined by
- * pos & blocksize) of a file is stored. The last element in the array
- * is NULL. Due to replication, a single block could be present on
- * multiple hosts.
- * @param fs The configured filesystem handle.
- * @param path The path of the file.
- * @param start The start of the block.
- * @param length The length of the block.
- * @return Returns a dynamically-allocated 2-d array of blocks-hosts;
- * NULL on error.
- */
- LIBHDFS_EXTERNAL
- char*** hdfsGetHosts(hdfsFS fs, const char* path,
- tOffset start, tOffset length);
-
-
- /**
- * hdfsFreeHosts - Free up the structure returned by hdfsGetHosts
- * @param hdfsFileInfo The array of dynamically-allocated hdfsFileInfo
- * objects.
- * @param numEntries The size of the array.
- */
- LIBHDFS_EXTERNAL
- void hdfsFreeHosts(char ***blockHosts);
-
-
- /**
- * hdfsGetDefaultBlockSize - Get the default blocksize.
- *
- * @param fs The configured filesystem handle.
- * @deprecated Use hdfsGetDefaultBlockSizeAtPath instead.
- *
- * @return Returns the default blocksize, or -1 on error.
- */
- LIBHDFS_EXTERNAL
- tOffset hdfsGetDefaultBlockSize(hdfsFS fs);
-
-
- /**
- * hdfsGetDefaultBlockSizeAtPath - Get the default blocksize at the
- * filesystem indicated by a given path.
- *
- * @param fs The configured filesystem handle.
- * @param path The given path will be used to locate the actual
- * filesystem. The full path does not have to exist.
- *
- * @return Returns the default blocksize, or -1 on error.
- */
- LIBHDFS_EXTERNAL
- tOffset hdfsGetDefaultBlockSizeAtPath(hdfsFS fs, const char *path);
-
-
- /**
- * hdfsGetCapacity - Return the raw capacity of the filesystem.
- * @param fs The configured filesystem handle.
- * @return Returns the raw-capacity; -1 on error.
- */
- LIBHDFS_EXTERNAL
- tOffset hdfsGetCapacity(hdfsFS fs);
-
-
- /**
- * hdfsGetUsed - Return the total raw size of all files in the filesystem.
- * @param fs The configured filesystem handle.
- * @return Returns the total-size; -1 on error.
- */
- LIBHDFS_EXTERNAL
- tOffset hdfsGetUsed(hdfsFS fs);
-
- /**
- * Change the user and/or group of a file or directory.
- *
- * @param fs The configured filesystem handle.
- * @param path the path to the file or directory
- * @param owner User string. Set to NULL for 'no change'
- * @param group Group string. Set to NULL for 'no change'
- * @return 0 on success else -1
- */
- LIBHDFS_EXTERNAL
- int hdfsChown(hdfsFS fs, const char* path, const char *owner,
- const char *group);
-
- /**
- * hdfsChmod
- * @param fs The configured filesystem handle.
- * @param path the path to the file or directory
- * @param mode the bitmask to set it to
- * @return 0 on success else -1
- */
- LIBHDFS_EXTERNAL
- int hdfsChmod(hdfsFS fs, const char* path, short mode);
-
- /**
- * hdfsUtime
- * @param fs The configured filesystem handle.
- * @param path the path to the file or directory
- * @param mtime new modification time or -1 for no change
- * @param atime new access time or -1 for no change
- * @return 0 on success else -1
- */
- LIBHDFS_EXTERNAL
- int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime);
-
- /**
- * Allocate a zero-copy options structure.
- *
- * You must free all options structures allocated with this function using
- * hadoopRzOptionsFree.
- *
- * @return A zero-copy options structure, or NULL if one could
- * not be allocated. If NULL is returned, errno will
- * contain the error number.
- */
- LIBHDFS_EXTERNAL
- struct hadoopRzOptions *hadoopRzOptionsAlloc(void);
-
- /**
- * Determine whether we should skip checksums in read0.
- *
- * @param opts The options structure.
- * @param skip Nonzero to skip checksums sometimes; zero to always
- * check them.
- *
- * @return 0 on success; -1 plus errno on failure.
- */
- LIBHDFS_EXTERNAL
- int hadoopRzOptionsSetSkipChecksum(
- struct hadoopRzOptions *opts, int skip);
-
- /**
- * Set the ByteBufferPool to use with read0.
- *
- * @param opts The options structure.
- * @param className If this is NULL, we will not use any
- * ByteBufferPool. If this is non-NULL, it will be
- * treated as the name of the pool class to use.
- * For example, you can use
- * ELASTIC_BYTE_BUFFER_POOL_CLASS.
- *
- * @return 0 if the ByteBufferPool class was found and
- * instantiated;
- * -1 plus errno otherwise.
- */
- LIBHDFS_EXTERNAL
- int hadoopRzOptionsSetByteBufferPool(
- struct hadoopRzOptions *opts, const char *className);
-
- /**
- * Free a hadoopRzOptionsFree structure.
- *
- * @param opts The options structure to free.
- * Any associated ByteBufferPool will also be freed.
- */
- LIBHDFS_EXTERNAL
- void hadoopRzOptionsFree(struct hadoopRzOptions *opts);
-
- /**
- * Perform a byte buffer read.
- * If possible, this will be a zero-copy (mmap) read.
- *
- * @param file The file to read from.
- * @param opts An options structure created by hadoopRzOptionsAlloc.
- * @param maxLength The maximum length to read. We may read fewer bytes
- * than this length.
- *
- * @return On success, we will return a new hadoopRzBuffer.
- * This buffer will continue to be valid and readable
- * until it is released by readZeroBufferFree. Failure to
- * release a buffer will lead to a memory leak.
- * You can access the data within the hadoopRzBuffer with
- * hadoopRzBufferGet. If you have reached EOF, the data
- * within the hadoopRzBuffer will be NULL. You must still
- * free hadoopRzBuffer instances containing NULL.
- *
- * On failure, we will return NULL plus an errno code.
- * errno = EOPNOTSUPP indicates that we could not do a
- * zero-copy read, and there was no ByteBufferPool
- * supplied.
- */
- LIBHDFS_EXTERNAL
- struct hadoopRzBuffer* hadoopReadZero(hdfsFile file,
- struct hadoopRzOptions *opts, int32_t maxLength);
-
- /**
- * Determine the length of the buffer returned from readZero.
- *
- * @param buffer a buffer returned from readZero.
- * @return the length of the buffer.
- */
- LIBHDFS_EXTERNAL
- int32_t hadoopRzBufferLength(const struct hadoopRzBuffer *buffer);
-
- /**
- * Get a pointer to the raw buffer returned from readZero.
- *
- * To find out how many bytes this buffer contains, call
- * hadoopRzBufferLength.
- *
- * @param buffer a buffer returned from readZero.
- * @return a pointer to the start of the buffer. This will be
- * NULL when end-of-file has been reached.
- */
- LIBHDFS_EXTERNAL
- const void *hadoopRzBufferGet(const struct hadoopRzBuffer *buffer);
-
- /**
- * Release a buffer obtained through readZero.
- *
- * @param file The hdfs stream that created this buffer. This must be
- * the same stream you called hadoopReadZero on.
- * @param buffer The buffer to release.
- */
- LIBHDFS_EXTERNAL
- void hadoopRzBufferFree(hdfsFile file, struct hadoopRzBuffer *buffer);
-
-#ifdef __cplusplus
-}
-#endif
-
-#undef LIBHDFS_EXTERNAL
-#endif /*LIBHDFS_HDFS_H*/
-
-/**
- * vim: ts=4: sw=4: et
- */
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs_test.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs_test.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs_test.h
deleted file mode 100644
index 0eab9a6..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/hdfs_test.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_HDFS_TEST_H
-#define LIBHDFS_HDFS_TEST_H
-
-struct hdfsFile_internal;
-
-/**
- * Some functions that are visible only for testing.
- *
- * This header is not meant to be exported or used outside of the libhdfs unit
- * tests.
- */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
- /**
- * Determine if a file is using the "direct read" optimization.
- *
- * @param file The HDFS file
- * @return 1 if the file is using the direct read optimization,
- * 0 otherwise.
- */
- int hdfsFileUsesDirectRead(struct hdfsFile_internal *file);
-
- /**
- * Disable the direct read optimization for a file.
- *
- * This is mainly provided for unit testing purposes.
- *
- * @param file The HDFS file
- */
- void hdfsFileDisableDirectRead(struct hdfsFile_internal *file);
-
- /**
- * Disable domain socket security checks.
- *
- * @param 0 if domain socket security was disabled;
- * -1 if not.
- */
- int hdfsDisableDomainSocketSecurity(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/jni_helper.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/jni_helper.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/jni_helper.c
deleted file mode 100644
index 50d9681..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/jni_helper.c
+++ /dev/null
@@ -1,595 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "config.h"
-#include "exception.h"
-#include "jni_helper.h"
-#include "platform.h"
-#include "common/htable.h"
-#include "os/mutexes.h"
-#include "os/thread_local_storage.h"
-
-#include <stdio.h>
-#include <string.h>
-
-static struct htable *gClassRefHTable = NULL;
-
-/** The Native return types that methods could return */
-#define JVOID 'V'
-#define JOBJECT 'L'
-#define JARRAYOBJECT '['
-#define JBOOLEAN 'Z'
-#define JBYTE 'B'
-#define JCHAR 'C'
-#define JSHORT 'S'
-#define JINT 'I'
-#define JLONG 'J'
-#define JFLOAT 'F'
-#define JDOUBLE 'D'
-
-
-/**
- * MAX_HASH_TABLE_ELEM: The maximum no. of entries in the hashtable.
- * It's set to 4096 to account for (classNames + No. of threads)
- */
-#define MAX_HASH_TABLE_ELEM 4096
-
-/**
- * Length of buffer for retrieving created JVMs. (We only ever create one.)
- */
-#define VM_BUF_LENGTH 1
-
-void destroyLocalReference(JNIEnv *env, jobject jObject)
-{
- if (jObject)
- (*env)->DeleteLocalRef(env, jObject);
-}
-
-static jthrowable validateMethodType(JNIEnv *env, MethType methType)
-{
- if (methType != STATIC && methType != INSTANCE) {
- return newRuntimeError(env, "validateMethodType(methType=%d): "
- "illegal method type.\n", methType);
- }
- return NULL;
-}
-
-jthrowable newJavaStr(JNIEnv *env, const char *str, jstring *out)
-{
- jstring jstr;
-
- if (!str) {
- /* Can't pass NULL to NewStringUTF: the result would be
- * implementation-defined. */
- *out = NULL;
- return NULL;
- }
- jstr = (*env)->NewStringUTF(env, str);
- if (!jstr) {
- /* If NewStringUTF returns NULL, an exception has been thrown,
- * which we need to handle. Probaly an OOM. */
- return getPendingExceptionAndClear(env);
- }
- *out = jstr;
- return NULL;
-}
-
-jthrowable newCStr(JNIEnv *env, jstring jstr, char **out)
-{
- const char *tmp;
-
- if (!jstr) {
- *out = NULL;
- return NULL;
- }
- tmp = (*env)->GetStringUTFChars(env, jstr, NULL);
- if (!tmp) {
- return getPendingExceptionAndClear(env);
- }
- *out = strdup(tmp);
- (*env)->ReleaseStringUTFChars(env, jstr, tmp);
- return NULL;
-}
-
-jthrowable invokeMethod(JNIEnv *env, jvalue *retval, MethType methType,
- jobject instObj, const char *className,
- const char *methName, const char *methSignature, ...)
-{
- va_list args;
- jclass cls;
- jmethodID mid;
- jthrowable jthr;
- const char *str;
- char returnType;
-
- jthr = validateMethodType(env, methType);
- if (jthr)
- return jthr;
- jthr = globalClassReference(className, env, &cls);
- if (jthr)
- return jthr;
- jthr = methodIdFromClass(className, methName, methSignature,
- methType, env, &mid);
- if (jthr)
- return jthr;
- str = methSignature;
- while (*str != ')') str++;
- str++;
- returnType = *str;
- va_start(args, methSignature);
- if (returnType == JOBJECT || returnType == JARRAYOBJECT) {
- jobject jobj = NULL;
- if (methType == STATIC) {
- jobj = (*env)->CallStaticObjectMethodV(env, cls, mid, args);
- }
- else if (methType == INSTANCE) {
- jobj = (*env)->CallObjectMethodV(env, instObj, mid, args);
- }
- retval->l = jobj;
- }
- else if (returnType == JVOID) {
- if (methType == STATIC) {
- (*env)->CallStaticVoidMethodV(env, cls, mid, args);
- }
- else if (methType == INSTANCE) {
- (*env)->CallVoidMethodV(env, instObj, mid, args);
- }
- }
- else if (returnType == JBOOLEAN) {
- jboolean jbool = 0;
- if (methType == STATIC) {
- jbool = (*env)->CallStaticBooleanMethodV(env, cls, mid, args);
- }
- else if (methType == INSTANCE) {
- jbool = (*env)->CallBooleanMethodV(env, instObj, mid, args);
- }
- retval->z = jbool;
- }
- else if (returnType == JSHORT) {
- jshort js = 0;
- if (methType == STATIC) {
- js = (*env)->CallStaticShortMethodV(env, cls, mid, args);
- }
- else if (methType == INSTANCE) {
- js = (*env)->CallShortMethodV(env, instObj, mid, args);
- }
- retval->s = js;
- }
- else if (returnType == JLONG) {
- jlong jl = -1;
- if (methType == STATIC) {
- jl = (*env)->CallStaticLongMethodV(env, cls, mid, args);
- }
- else if (methType == INSTANCE) {
- jl = (*env)->CallLongMethodV(env, instObj, mid, args);
- }
- retval->j = jl;
- }
- else if (returnType == JINT) {
- jint ji = -1;
- if (methType == STATIC) {
- ji = (*env)->CallStaticIntMethodV(env, cls, mid, args);
- }
- else if (methType == INSTANCE) {
- ji = (*env)->CallIntMethodV(env, instObj, mid, args);
- }
- retval->i = ji;
- }
- va_end(args);
-
- jthr = (*env)->ExceptionOccurred(env);
- if (jthr) {
- (*env)->ExceptionClear(env);
- return jthr;
- }
- return NULL;
-}
-
-jthrowable constructNewObjectOfClass(JNIEnv *env, jobject *out, const char *className,
- const char *ctorSignature, ...)
-{
- va_list args;
- jclass cls;
- jmethodID mid;
- jobject jobj;
- jthrowable jthr;
-
- jthr = globalClassReference(className, env, &cls);
- if (jthr)
- return jthr;
- jthr = methodIdFromClass(className, "<init>", ctorSignature,
- INSTANCE, env, &mid);
- if (jthr)
- return jthr;
- va_start(args, ctorSignature);
- jobj = (*env)->NewObjectV(env, cls, mid, args);
- va_end(args);
- if (!jobj)
- return getPendingExceptionAndClear(env);
- *out = jobj;
- return NULL;
-}
-
-
-jthrowable methodIdFromClass(const char *className, const char *methName,
- const char *methSignature, MethType methType,
- JNIEnv *env, jmethodID *out)
-{
- jclass cls;
- jthrowable jthr;
- jmethodID mid = 0;
-
- jthr = globalClassReference(className, env, &cls);
- if (jthr)
- return jthr;
- jthr = validateMethodType(env, methType);
- if (jthr)
- return jthr;
- if (methType == STATIC) {
- mid = (*env)->GetStaticMethodID(env, cls, methName, methSignature);
- }
- else if (methType == INSTANCE) {
- mid = (*env)->GetMethodID(env, cls, methName, methSignature);
- }
- if (mid == NULL) {
- fprintf(stderr, "could not find method %s from class %s with "
- "signature %s\n", methName, className, methSignature);
- return getPendingExceptionAndClear(env);
- }
- *out = mid;
- return NULL;
-}
-
-jthrowable globalClassReference(const char *className, JNIEnv *env, jclass *out)
-{
- jthrowable jthr = NULL;
- jclass local_clazz = NULL;
- jclass clazz = NULL;
- int ret;
-
- mutexLock(&hdfsHashMutex);
- if (!gClassRefHTable) {
- gClassRefHTable = htable_alloc(MAX_HASH_TABLE_ELEM, ht_hash_string,
- ht_compare_string);
- if (!gClassRefHTable) {
- jthr = newRuntimeError(env, "htable_alloc failed\n");
- goto done;
- }
- }
- clazz = htable_get(gClassRefHTable, className);
- if (clazz) {
- *out = clazz;
- goto done;
- }
- local_clazz = (*env)->FindClass(env,className);
- if (!local_clazz) {
- jthr = getPendingExceptionAndClear(env);
- goto done;
- }
- clazz = (*env)->NewGlobalRef(env, local_clazz);
- if (!clazz) {
- jthr = getPendingExceptionAndClear(env);
- goto done;
- }
- ret = htable_put(gClassRefHTable, (void*)className, clazz);
- if (ret) {
- jthr = newRuntimeError(env, "htable_put failed with error "
- "code %d\n", ret);
- goto done;
- }
- *out = clazz;
- jthr = NULL;
-done:
- mutexUnlock(&hdfsHashMutex);
- (*env)->DeleteLocalRef(env, local_clazz);
- if (jthr && clazz) {
- (*env)->DeleteGlobalRef(env, clazz);
- }
- return jthr;
-}
-
-jthrowable classNameOfObject(jobject jobj, JNIEnv *env, char **name)
-{
- jthrowable jthr;
- jclass cls, clsClass = NULL;
- jmethodID mid;
- jstring str = NULL;
- const char *cstr = NULL;
- char *newstr;
-
- cls = (*env)->GetObjectClass(env, jobj);
- if (cls == NULL) {
- jthr = getPendingExceptionAndClear(env);
- goto done;
- }
- clsClass = (*env)->FindClass(env, "java/lang/Class");
- if (clsClass == NULL) {
- jthr = getPendingExceptionAndClear(env);
- goto done;
- }
- mid = (*env)->GetMethodID(env, clsClass, "getName", "()Ljava/lang/String;");
- if (mid == NULL) {
- jthr = getPendingExceptionAndClear(env);
- goto done;
- }
- str = (*env)->CallObjectMethod(env, cls, mid);
- if (str == NULL) {
- jthr = getPendingExceptionAndClear(env);
- goto done;
- }
- cstr = (*env)->GetStringUTFChars(env, str, NULL);
- if (!cstr) {
- jthr = getPendingExceptionAndClear(env);
- goto done;
- }
- newstr = strdup(cstr);
- if (newstr == NULL) {
- jthr = newRuntimeError(env, "classNameOfObject: out of memory");
- goto done;
- }
- *name = newstr;
- jthr = NULL;
-
-done:
- destroyLocalReference(env, cls);
- destroyLocalReference(env, clsClass);
- if (str) {
- if (cstr)
- (*env)->ReleaseStringUTFChars(env, str, cstr);
- (*env)->DeleteLocalRef(env, str);
- }
- return jthr;
-}
-
-
-/**
- * Get the global JNI environemnt.
- *
- * We only have to create the JVM once. After that, we can use it in
- * every thread. You must be holding the jvmMutex when you call this
- * function.
- *
- * @return The JNIEnv on success; error code otherwise
- */
-static JNIEnv* getGlobalJNIEnv(void)
-{
- JavaVM* vmBuf[VM_BUF_LENGTH];
- JNIEnv *env;
- jint rv = 0;
- jint noVMs = 0;
- jthrowable jthr;
- char *hadoopClassPath;
- const char *hadoopClassPathVMArg = "-Djava.class.path=";
- size_t optHadoopClassPathLen;
- char *optHadoopClassPath;
- int noArgs = 1;
- char *hadoopJvmArgs;
- char jvmArgDelims[] = " ";
- char *str, *token, *savePtr;
- JavaVMInitArgs vm_args;
- JavaVM *vm;
- JavaVMOption *options;
-
- rv = JNI_GetCreatedJavaVMs(&(vmBuf[0]), VM_BUF_LENGTH, &noVMs);
- if (rv != 0) {
- fprintf(stderr, "JNI_GetCreatedJavaVMs failed with error: %d\n", rv);
- return NULL;
- }
-
- if (noVMs == 0) {
- //Get the environment variables for initializing the JVM
- hadoopClassPath = getenv("CLASSPATH");
- if (hadoopClassPath == NULL) {
- fprintf(stderr, "Environment variable CLASSPATH not set!\n");
- return NULL;
- }
- optHadoopClassPathLen = strlen(hadoopClassPath) +
- strlen(hadoopClassPathVMArg) + 1;
- optHadoopClassPath = malloc(sizeof(char)*optHadoopClassPathLen);
- snprintf(optHadoopClassPath, optHadoopClassPathLen,
- "%s%s", hadoopClassPathVMArg, hadoopClassPath);
-
- // Determine the # of LIBHDFS_OPTS args
- hadoopJvmArgs = getenv("LIBHDFS_OPTS");
- if (hadoopJvmArgs != NULL) {
- hadoopJvmArgs = strdup(hadoopJvmArgs);
- for (noArgs = 1, str = hadoopJvmArgs; ; noArgs++, str = NULL) {
- token = strtok_r(str, jvmArgDelims, &savePtr);
- if (NULL == token) {
- break;
- }
- }
- free(hadoopJvmArgs);
- }
-
- // Now that we know the # args, populate the options array
- options = calloc(noArgs, sizeof(JavaVMOption));
- if (!options) {
- fputs("Call to calloc failed\n", stderr);
- free(optHadoopClassPath);
- return NULL;
- }
- options[0].optionString = optHadoopClassPath;
- hadoopJvmArgs = getenv("LIBHDFS_OPTS");
- if (hadoopJvmArgs != NULL) {
- hadoopJvmArgs = strdup(hadoopJvmArgs);
- for (noArgs = 1, str = hadoopJvmArgs; ; noArgs++, str = NULL) {
- token = strtok_r(str, jvmArgDelims, &savePtr);
- if (NULL == token) {
- break;
- }
- options[noArgs].optionString = token;
- }
- }
-
- //Create the VM
- vm_args.version = JNI_VERSION_1_2;
- vm_args.options = options;
- vm_args.nOptions = noArgs;
- vm_args.ignoreUnrecognized = 1;
-
- rv = JNI_CreateJavaVM(&vm, (void*)&env, &vm_args);
-
- if (hadoopJvmArgs != NULL) {
- free(hadoopJvmArgs);
- }
- free(optHadoopClassPath);
- free(options);
-
- if (rv != 0) {
- fprintf(stderr, "Call to JNI_CreateJavaVM failed "
- "with error: %d\n", rv);
- return NULL;
- }
- jthr = invokeMethod(env, NULL, STATIC, NULL,
- "org/apache/hadoop/fs/FileSystem",
- "loadFileSystems", "()V");
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL, "loadFileSystems");
- }
- }
- else {
- //Attach this thread to the VM
- vm = vmBuf[0];
- rv = (*vm)->AttachCurrentThread(vm, (void*)&env, 0);
- if (rv != 0) {
- fprintf(stderr, "Call to AttachCurrentThread "
- "failed with error: %d\n", rv);
- return NULL;
- }
- }
-
- return env;
-}
-
-/**
- * getJNIEnv: A helper function to get the JNIEnv* for the given thread.
- * If no JVM exists, then one will be created. JVM command line arguments
- * are obtained from the LIBHDFS_OPTS environment variable.
- *
- * Implementation note: we rely on POSIX thread-local storage (tls).
- * This allows us to associate a destructor function with each thread, that
- * will detach the thread from the Java VM when the thread terminates. If we
- * failt to do this, it will cause a memory leak.
- *
- * However, POSIX TLS is not the most efficient way to do things. It requires a
- * key to be initialized before it can be used. Since we don't know if this key
- * is initialized at the start of this function, we have to lock a mutex first
- * and check. Luckily, most operating systems support the more efficient
- * __thread construct, which is initialized by the linker.
- *
- * @param: None.
- * @return The JNIEnv* corresponding to the thread.
- */
-JNIEnv* getJNIEnv(void)
-{
- JNIEnv *env;
- THREAD_LOCAL_STORAGE_GET_QUICK();
- mutexLock(&jvmMutex);
- if (threadLocalStorageGet(&env)) {
- mutexUnlock(&jvmMutex);
- return NULL;
- }
- if (env) {
- mutexUnlock(&jvmMutex);
- return env;
- }
-
- env = getGlobalJNIEnv();
- mutexUnlock(&jvmMutex);
- if (!env) {
- fprintf(stderr, "getJNIEnv: getGlobalJNIEnv failed\n");
- return NULL;
- }
- if (threadLocalStorageSet(env)) {
- return NULL;
- }
- THREAD_LOCAL_STORAGE_SET_QUICK(env);
- return env;
-}
-
-int javaObjectIsOfClass(JNIEnv *env, jobject obj, const char *name)
-{
- jclass clazz;
- int ret;
-
- clazz = (*env)->FindClass(env, name);
- if (!clazz) {
- printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "javaObjectIsOfClass(%s)", name);
- return -1;
- }
- ret = (*env)->IsInstanceOf(env, obj, clazz);
- (*env)->DeleteLocalRef(env, clazz);
- return ret == JNI_TRUE ? 1 : 0;
-}
-
-jthrowable hadoopConfSetStr(JNIEnv *env, jobject jConfiguration,
- const char *key, const char *value)
-{
- jthrowable jthr;
- jstring jkey = NULL, jvalue = NULL;
-
- jthr = newJavaStr(env, key, &jkey);
- if (jthr)
- goto done;
- jthr = newJavaStr(env, value, &jvalue);
- if (jthr)
- goto done;
- jthr = invokeMethod(env, NULL, INSTANCE, jConfiguration,
- "org/apache/hadoop/conf/Configuration", "set",
- "(Ljava/lang/String;Ljava/lang/String;)V",
- jkey, jvalue);
- if (jthr)
- goto done;
-done:
- (*env)->DeleteLocalRef(env, jkey);
- (*env)->DeleteLocalRef(env, jvalue);
- return jthr;
-}
-
-jthrowable fetchEnumInstance(JNIEnv *env, const char *className,
- const char *valueName, jobject *out)
-{
- jclass clazz;
- jfieldID fieldId;
- jobject jEnum;
- char prettyClass[256];
-
- clazz = (*env)->FindClass(env, className);
- if (!clazz) {
- return newRuntimeError(env, "fetchEnum(%s, %s): failed to find class.",
- className, valueName);
- }
- if (snprintf(prettyClass, sizeof(prettyClass), "L%s;", className)
- >= sizeof(prettyClass)) {
- return newRuntimeError(env, "fetchEnum(%s, %s): class name too long.",
- className, valueName);
- }
- fieldId = (*env)->GetStaticFieldID(env, clazz, valueName, prettyClass);
- if (!fieldId) {
- return getPendingExceptionAndClear(env);
- }
- jEnum = (*env)->GetStaticObjectField(env, clazz, fieldId);
- if (!jEnum) {
- return getPendingExceptionAndClear(env);
- }
- *out = jEnum;
- return NULL;
-}
-
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/jni_helper.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/jni_helper.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/jni_helper.h
deleted file mode 100644
index 90accc7..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/jni_helper.h
+++ /dev/null
@@ -1,161 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_JNI_HELPER_H
-#define LIBHDFS_JNI_HELPER_H
-
-#include <jni.h>
-#include <stdio.h>
-
-#include <stdlib.h>
-#include <stdarg.h>
-#include <errno.h>
-
-#define PATH_SEPARATOR ':'
-
-
-/** Denote the method we want to invoke as STATIC or INSTANCE */
-typedef enum {
- STATIC,
- INSTANCE
-} MethType;
-
-/**
- * Create a new malloc'ed C string from a Java string.
- *
- * @param env The JNI environment
- * @param jstr The Java string
- * @param out (out param) the malloc'ed C string
- *
- * @return NULL on success; the exception otherwise
- */
-jthrowable newCStr(JNIEnv *env, jstring jstr, char **out);
-
-/**
- * Create a new Java string from a C string.
- *
- * @param env The JNI environment
- * @param str The C string
- * @param out (out param) the java string
- *
- * @return NULL on success; the exception otherwise
- */
-jthrowable newJavaStr(JNIEnv *env, const char *str, jstring *out);
-
-/**
- * Helper function to destroy a local reference of java.lang.Object
- * @param env: The JNIEnv pointer.
- * @param jFile: The local reference of java.lang.Object object
- * @return None.
- */
-void destroyLocalReference(JNIEnv *env, jobject jObject);
-
-/** invokeMethod: Invoke a Static or Instance method.
- * className: Name of the class where the method can be found
- * methName: Name of the method
- * methSignature: the signature of the method "(arg-types)ret-type"
- * methType: The type of the method (STATIC or INSTANCE)
- * instObj: Required if the methType is INSTANCE. The object to invoke
- the method on.
- * env: The JNIEnv pointer
- * retval: The pointer to a union type which will contain the result of the
- method invocation, e.g. if the method returns an Object, retval will be
- set to that, if the method returns boolean, retval will be set to the
- value (JNI_TRUE or JNI_FALSE), etc.
- * exc: If the methods throws any exception, this will contain the reference
- * Arguments (the method arguments) must be passed after methSignature
- * RETURNS: -1 on error and 0 on success. If -1 is returned, exc will have
- a valid exception reference, and the result stored at retval is undefined.
- */
-jthrowable invokeMethod(JNIEnv *env, jvalue *retval, MethType methType,
- jobject instObj, const char *className, const char *methName,
- const char *methSignature, ...);
-
-jthrowable constructNewObjectOfClass(JNIEnv *env, jobject *out, const char *className,
- const char *ctorSignature, ...);
-
-jthrowable methodIdFromClass(const char *className, const char *methName,
- const char *methSignature, MethType methType,
- JNIEnv *env, jmethodID *out);
-
-jthrowable globalClassReference(const char *className, JNIEnv *env, jclass *out);
-
-/** classNameOfObject: Get an object's class name.
- * @param jobj: The object.
- * @param env: The JNIEnv pointer.
- * @param name: (out param) On success, will contain a string containing the
- * class name. This string must be freed by the caller.
- * @return NULL on success, or the exception
- */
-jthrowable classNameOfObject(jobject jobj, JNIEnv *env, char **name);
-
-/** getJNIEnv: A helper function to get the JNIEnv* for the given thread.
- * If no JVM exists, then one will be created. JVM command line arguments
- * are obtained from the LIBHDFS_OPTS environment variable.
- * @param: None.
- * @return The JNIEnv* corresponding to the thread.
- * */
-JNIEnv* getJNIEnv(void);
-
-/**
- * Figure out if a Java object is an instance of a particular class.
- *
- * @param env The Java environment.
- * @param obj The object to check.
- * @param name The class name to check.
- *
- * @return -1 if we failed to find the referenced class name.
- * 0 if the object is not of the given class.
- * 1 if the object is of the given class.
- */
-int javaObjectIsOfClass(JNIEnv *env, jobject obj, const char *name);
-
-/**
- * Set a value in a configuration object.
- *
- * @param env The JNI environment
- * @param jConfiguration The configuration object to modify
- * @param key The key to modify
- * @param value The value to set the key to
- *
- * @return NULL on success; exception otherwise
- */
-jthrowable hadoopConfSetStr(JNIEnv *env, jobject jConfiguration,
- const char *key, const char *value);
-
-/**
- * Fetch an instance of an Enum.
- *
- * @param env The JNI environment.
- * @param className The enum class name.
- * @param valueName The name of the enum value
- * @param out (out param) on success, a local reference to an
- * instance of the enum object. (Since Java enums are
- * singletones, this is also the only instance.)
- *
- * @return NULL on success; exception otherwise
- */
-jthrowable fetchEnumInstance(JNIEnv *env, const char *className,
- const char *valueName, jobject *out);
-
-#endif /*LIBHDFS_JNI_HELPER_H*/
-
-/**
- * vim: ts=4: sw=4: et:
- */
-
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/native_mini_dfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/native_mini_dfs.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/native_mini_dfs.c
deleted file mode 100644
index b36ef76..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/native_mini_dfs.c
+++ /dev/null
@@ -1,357 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "exception.h"
-#include "jni_helper.h"
-#include "native_mini_dfs.h"
-#include "platform.h"
-
-#include <errno.h>
-#include <jni.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#ifndef EINTERNAL
-#define EINTERNAL 255
-#endif
-
-#define MINIDFS_CLUSTER_BUILDER "org/apache/hadoop/hdfs/MiniDFSCluster$Builder"
-#define MINIDFS_CLUSTER "org/apache/hadoop/hdfs/MiniDFSCluster"
-#define HADOOP_CONF "org/apache/hadoop/conf/Configuration"
-#define HADOOP_NAMENODE "org/apache/hadoop/hdfs/server/namenode/NameNode"
-#define JAVA_INETSOCKETADDRESS "java/net/InetSocketAddress"
-
-struct NativeMiniDfsCluster {
- /**
- * The NativeMiniDfsCluster object
- */
- jobject obj;
-
- /**
- * Path to the domain socket, or the empty string if there is none.
- */
- char domainSocketPath[PATH_MAX];
-};
-
-static int hdfsDisableDomainSocketSecurity(void)
-{
- jthrowable jthr;
- JNIEnv* env = getJNIEnv();
- if (env == NULL) {
- errno = EINTERNAL;
- return -1;
- }
- jthr = invokeMethod(env, NULL, STATIC, NULL,
- "org/apache/hadoop/net/unix/DomainSocket",
- "disableBindPathValidation", "()V");
- if (jthr) {
- errno = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "DomainSocket#disableBindPathValidation");
- return -1;
- }
- return 0;
-}
-
-static jthrowable nmdConfigureShortCircuit(JNIEnv *env,
- struct NativeMiniDfsCluster *cl, jobject cobj)
-{
- jthrowable jthr;
- char *tmpDir;
-
- int ret = hdfsDisableDomainSocketSecurity();
- if (ret) {
- return newRuntimeError(env, "failed to disable hdfs domain "
- "socket security: error %d", ret);
- }
- jthr = hadoopConfSetStr(env, cobj, "dfs.client.read.shortcircuit", "true");
- if (jthr) {
- return jthr;
- }
- tmpDir = getenv("TMPDIR");
- if (!tmpDir) {
- tmpDir = "/tmp";
- }
- snprintf(cl->domainSocketPath, PATH_MAX, "%s/native_mini_dfs.sock.%d.%d",
- tmpDir, getpid(), rand());
- snprintf(cl->domainSocketPath, PATH_MAX, "%s/native_mini_dfs.sock.%d.%d",
- tmpDir, getpid(), rand());
- jthr = hadoopConfSetStr(env, cobj, "dfs.domain.socket.path",
- cl->domainSocketPath);
- if (jthr) {
- return jthr;
- }
- return NULL;
-}
-
-struct NativeMiniDfsCluster* nmdCreate(struct NativeMiniDfsConf *conf)
-{
- struct NativeMiniDfsCluster* cl = NULL;
- jobject bld = NULL, cobj = NULL, cluster = NULL;
- jvalue val;
- JNIEnv *env = getJNIEnv();
- jthrowable jthr;
- jstring jconfStr = NULL;
-
- if (!env) {
- fprintf(stderr, "nmdCreate: unable to construct JNIEnv.\n");
- return NULL;
- }
- cl = calloc(1, sizeof(struct NativeMiniDfsCluster));
- if (!cl) {
- fprintf(stderr, "nmdCreate: OOM");
- goto error;
- }
- jthr = constructNewObjectOfClass(env, &cobj, HADOOP_CONF, "()V");
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdCreate: new Configuration");
- goto error;
- }
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdCreate: Configuration::setBoolean");
- goto error;
- }
- // Disable 'minimum block size' -- it's annoying in tests.
- (*env)->DeleteLocalRef(env, jconfStr);
- jconfStr = NULL;
- jthr = newJavaStr(env, "dfs.namenode.fs-limits.min-block-size", &jconfStr);
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdCreate: new String");
- goto error;
- }
- jthr = invokeMethod(env, NULL, INSTANCE, cobj, HADOOP_CONF,
- "setLong", "(Ljava/lang/String;J)V", jconfStr, 0LL);
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdCreate: Configuration::setLong");
- goto error;
- }
- // Creae MiniDFSCluster object
- jthr = constructNewObjectOfClass(env, &bld, MINIDFS_CLUSTER_BUILDER,
- "(L"HADOOP_CONF";)V", cobj);
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdCreate: NativeMiniDfsCluster#Builder#Builder");
- goto error;
- }
- if (conf->configureShortCircuit) {
- jthr = nmdConfigureShortCircuit(env, cl, cobj);
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdCreate: nmdConfigureShortCircuit error");
- goto error;
- }
- }
- jthr = invokeMethod(env, &val, INSTANCE, bld, MINIDFS_CLUSTER_BUILDER,
- "format", "(Z)L" MINIDFS_CLUSTER_BUILDER ";", conf->doFormat);
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL, "nmdCreate: "
- "Builder::format");
- goto error;
- }
- (*env)->DeleteLocalRef(env, val.l);
- if (conf->webhdfsEnabled) {
- jthr = invokeMethod(env, &val, INSTANCE, bld, MINIDFS_CLUSTER_BUILDER,
- "nameNodeHttpPort", "(I)L" MINIDFS_CLUSTER_BUILDER ";",
- conf->namenodeHttpPort);
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL, "nmdCreate: "
- "Builder::nameNodeHttpPort");
- goto error;
- }
- (*env)->DeleteLocalRef(env, val.l);
- }
- jthr = invokeMethod(env, &val, INSTANCE, bld, MINIDFS_CLUSTER_BUILDER,
- "build", "()L" MINIDFS_CLUSTER ";");
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdCreate: Builder#build");
- goto error;
- }
- cluster = val.l;
- cl->obj = (*env)->NewGlobalRef(env, val.l);
- if (!cl->obj) {
- printPendingExceptionAndFree(env, PRINT_EXC_ALL,
- "nmdCreate: NewGlobalRef");
- goto error;
- }
- (*env)->DeleteLocalRef(env, cluster);
- (*env)->DeleteLocalRef(env, bld);
- (*env)->DeleteLocalRef(env, cobj);
- (*env)->DeleteLocalRef(env, jconfStr);
- return cl;
-
-error:
- (*env)->DeleteLocalRef(env, cluster);
- (*env)->DeleteLocalRef(env, bld);
- (*env)->DeleteLocalRef(env, cobj);
- (*env)->DeleteLocalRef(env, jconfStr);
- free(cl);
- return NULL;
-}
-
-void nmdFree(struct NativeMiniDfsCluster* cl)
-{
- JNIEnv *env = getJNIEnv();
- if (!env) {
- fprintf(stderr, "nmdFree: getJNIEnv failed\n");
- free(cl);
- return;
- }
- (*env)->DeleteGlobalRef(env, cl->obj);
- free(cl);
-}
-
-int nmdShutdown(struct NativeMiniDfsCluster* cl)
-{
- JNIEnv *env = getJNIEnv();
- jthrowable jthr;
-
- if (!env) {
- fprintf(stderr, "nmdShutdown: getJNIEnv failed\n");
- return -EIO;
- }
- jthr = invokeMethod(env, NULL, INSTANCE, cl->obj,
- MINIDFS_CLUSTER, "shutdown", "()V");
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdShutdown: MiniDFSCluster#shutdown");
- return -EIO;
- }
- return 0;
-}
-
-int nmdWaitClusterUp(struct NativeMiniDfsCluster *cl)
-{
- jthrowable jthr;
- JNIEnv *env = getJNIEnv();
- if (!env) {
- fprintf(stderr, "nmdWaitClusterUp: getJNIEnv failed\n");
- return -EIO;
- }
- jthr = invokeMethod(env, NULL, INSTANCE, cl->obj,
- MINIDFS_CLUSTER, "waitClusterUp", "()V");
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdWaitClusterUp: MiniDFSCluster#waitClusterUp ");
- return -EIO;
- }
- return 0;
-}
-
-int nmdGetNameNodePort(const struct NativeMiniDfsCluster *cl)
-{
- JNIEnv *env = getJNIEnv();
- jvalue jVal;
- jthrowable jthr;
-
- if (!env) {
- fprintf(stderr, "nmdHdfsConnect: getJNIEnv failed\n");
- return -EIO;
- }
- // Note: this will have to be updated when HA nativeMiniDfs clusters are
- // supported
- jthr = invokeMethod(env, &jVal, INSTANCE, cl->obj,
- MINIDFS_CLUSTER, "getNameNodePort", "()I");
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdHdfsConnect: MiniDFSCluster#getNameNodePort");
- return -EIO;
- }
- return jVal.i;
-}
-
-int nmdGetNameNodeHttpAddress(const struct NativeMiniDfsCluster *cl,
- int *port, const char **hostName)
-{
- JNIEnv *env = getJNIEnv();
- jvalue jVal;
- jobject jNameNode, jAddress;
- jthrowable jthr;
- int ret = 0;
- const char *host;
-
- if (!env) {
- fprintf(stderr, "nmdHdfsConnect: getJNIEnv failed\n");
- return -EIO;
- }
- // First get the (first) NameNode of the cluster
- jthr = invokeMethod(env, &jVal, INSTANCE, cl->obj, MINIDFS_CLUSTER,
- "getNameNode", "()L" HADOOP_NAMENODE ";");
- if (jthr) {
- printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdGetNameNodeHttpAddress: "
- "MiniDFSCluster#getNameNode");
- return -EIO;
- }
- jNameNode = jVal.l;
-
- // Then get the http address (InetSocketAddress) of the NameNode
- jthr = invokeMethod(env, &jVal, INSTANCE, jNameNode, HADOOP_NAMENODE,
- "getHttpAddress", "()L" JAVA_INETSOCKETADDRESS ";");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdGetNameNodeHttpAddress: "
- "NameNode#getHttpAddress");
- goto error_dlr_nn;
- }
- jAddress = jVal.l;
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jAddress,
- JAVA_INETSOCKETADDRESS, "getPort", "()I");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdGetNameNodeHttpAddress: "
- "InetSocketAddress#getPort");
- goto error_dlr_addr;
- }
- *port = jVal.i;
-
- jthr = invokeMethod(env, &jVal, INSTANCE, jAddress, JAVA_INETSOCKETADDRESS,
- "getHostName", "()Ljava/lang/String;");
- if (jthr) {
- ret = printExceptionAndFree(env, jthr, PRINT_EXC_ALL,
- "nmdGetNameNodeHttpAddress: "
- "InetSocketAddress#getHostName");
- goto error_dlr_addr;
- }
- host = (*env)->GetStringUTFChars(env, jVal.l, NULL);
- *hostName = strdup(host);
- (*env)->ReleaseStringUTFChars(env, jVal.l, host);
-
-error_dlr_addr:
- (*env)->DeleteLocalRef(env, jAddress);
-error_dlr_nn:
- (*env)->DeleteLocalRef(env, jNameNode);
-
- return ret;
-}
-
-const char *hdfsGetDomainSocketPath(const struct NativeMiniDfsCluster *cl) {
- if (cl->domainSocketPath[0]) {
- return cl->domainSocketPath;
- }
-
- return NULL;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/native_mini_dfs.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/native_mini_dfs.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/native_mini_dfs.h
deleted file mode 100644
index ce8b1cf..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/native_mini_dfs.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_NATIVE_MINI_DFS_H
-#define LIBHDFS_NATIVE_MINI_DFS_H
-
-#include <jni.h> /* for jboolean */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct hdfsBuilder;
-struct NativeMiniDfsCluster;
-
-/**
- * Represents a configuration to use for creating a Native MiniDFSCluster
- */
-struct NativeMiniDfsConf {
- /**
- * Nonzero if the cluster should be formatted prior to startup.
- */
- jboolean doFormat;
-
- /**
- * Whether or not to enable webhdfs in MiniDfsCluster
- */
- jboolean webhdfsEnabled;
-
- /**
- * The http port of the namenode in MiniDfsCluster
- */
- jint namenodeHttpPort;
-
- /**
- * Nonzero if we should configure short circuit.
- */
- jboolean configureShortCircuit;
-};
-
-/**
- * Create a NativeMiniDfsBuilder
- *
- * @param conf (inout) The cluster configuration
- *
- * @return a NativeMiniDfsBuilder, or a NULL pointer on error.
- */
-struct NativeMiniDfsCluster* nmdCreate(struct NativeMiniDfsConf *conf);
-
-/**
- * Wait until a MiniDFSCluster comes out of safe mode.
- *
- * @param cl The cluster
- *
- * @return 0 on success; a non-zero error code if the cluster fails to
- * come out of safe mode.
- */
-int nmdWaitClusterUp(struct NativeMiniDfsCluster *cl);
-
-/**
- * Shut down a NativeMiniDFS cluster
- *
- * @param cl The cluster
- *
- * @return 0 on success; a non-zero error code if an exception is
- * thrown.
- */
-int nmdShutdown(struct NativeMiniDfsCluster *cl);
-
-/**
- * Destroy a Native MiniDFSCluster
- *
- * @param cl The cluster to destroy
- */
-void nmdFree(struct NativeMiniDfsCluster* cl);
-
-/**
- * Get the port that's in use by the given (non-HA) nativeMiniDfs
- *
- * @param cl The initialized NativeMiniDfsCluster
- *
- * @return the port, or a negative error code
- */
-int nmdGetNameNodePort(const struct NativeMiniDfsCluster *cl);
-
-/**
- * Get the http address that's in use by the given (non-HA) nativeMiniDfs
- *
- * @param cl The initialized NativeMiniDfsCluster
- * @param port Used to capture the http port of the NameNode
- * of the NativeMiniDfsCluster
- * @param hostName Used to capture the http hostname of the NameNode
- * of the NativeMiniDfsCluster
- *
- * @return 0 on success; a non-zero error code if failing to
- * get the information.
- */
-int nmdGetNameNodeHttpAddress(const struct NativeMiniDfsCluster *cl,
- int *port, const char **hostName);
-
-/**
- * Get domain socket path set for this cluster.
- *
- * @param cl The cluster
- *
- * @return A const string of domain socket path, or NULL if not set.
- */
-const char *hdfsGetDomainSocketPath(const struct NativeMiniDfsCluster *cl);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/mutexes.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/mutexes.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/mutexes.h
deleted file mode 100644
index da30bf4..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/mutexes.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_MUTEXES_H
-#define LIBHDFS_MUTEXES_H
-
-/*
- * Defines abstraction over platform-specific mutexes. libhdfs has no formal
- * initialization function that users would call from a single-threaded context
- * to initialize the library. This creates a challenge for bootstrapping the
- * mutexes. To address this, all required mutexes are pre-defined here with
- * external storage. Platform-specific implementations must guarantee that the
- * mutexes are initialized via static initialization.
- */
-
-#include "platform.h"
-
-/** Mutex protecting the class reference hash table. */
-extern mutex hdfsHashMutex;
-
-/** Mutex protecting singleton JVM instance. */
-extern mutex jvmMutex;
-
-/**
- * Locks a mutex.
- *
- * @param m mutex
- * @return 0 if successful, non-zero otherwise
- */
-int mutexLock(mutex *m);
-
-/**
- * Unlocks a mutex.
- *
- * @param m mutex
- * @return 0 if successful, non-zero otherwise
- */
-int mutexUnlock(mutex *m);
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/mutexes.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/mutexes.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/mutexes.c
deleted file mode 100644
index c4c2f26..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/mutexes.c
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "os/mutexes.h"
-
-#include <pthread.h>
-#include <stdio.h>
-
-mutex hdfsHashMutex = PTHREAD_MUTEX_INITIALIZER;
-mutex jvmMutex = PTHREAD_MUTEX_INITIALIZER;
-
-int mutexLock(mutex *m) {
- int ret = pthread_mutex_lock(m);
- if (ret) {
- fprintf(stderr, "mutexLock: pthread_mutex_lock failed with error %d\n",
- ret);
- }
- return ret;
-}
-
-int mutexUnlock(mutex *m) {
- int ret = pthread_mutex_unlock(m);
- if (ret) {
- fprintf(stderr, "mutexUnlock: pthread_mutex_unlock failed with error %d\n",
- ret);
- }
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/platform.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/platform.h b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/platform.h
deleted file mode 100644
index c63bbf9..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/platform.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#ifndef LIBHDFS_PLATFORM_H
-#define LIBHDFS_PLATFORM_H
-
-#include <pthread.h>
-
-/* Use gcc type-checked format arguments. */
-#define TYPE_CHECKED_PRINTF_FORMAT(formatArg, varArgs) \
- __attribute__((format(printf, formatArg, varArgs)))
-
-/*
- * Mutex and thread data types defined by pthreads.
- */
-typedef pthread_mutex_t mutex;
-typedef pthread_t threadId;
-
-#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/thread.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/thread.c b/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/thread.c
deleted file mode 100644
index af0c61f..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/native/libhdfs/os/posix/thread.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-#include "os/thread.h"
-
-#include <pthread.h>
-#include <stdio.h>
-
-/**
- * Defines a helper function that adapts function pointer provided by caller to
- * the type required by pthread_create.
- *
- * @param toRun thread to run
- * @return void* result of running thread (always NULL)
- */
-static void* runThread(void *toRun) {
- const thread *t = toRun;
- t->start(t->arg);
- return NULL;
-}
-
-int threadCreate(thread *t) {
- int ret;
- ret = pthread_create(&t->id, NULL, runThread, t);
- if (ret) {
- fprintf(stderr, "threadCreate: pthread_create failed with error %d\n", ret);
- }
- return ret;
-}
-
-int threadJoin(const thread *t) {
- int ret = pthread_join(t->id, NULL);
- if (ret) {
- fprintf(stderr, "threadJoin: pthread_join failed with error %d\n", ret);
- }
- return ret;
-}
[04/35] hadoop git commit: HDFS-9206. Inconsistent default value of
dfs.datanode.stripedread.buffer.size. Contributed by Walter Su.
Posted by ji...@apache.org.
HDFS-9206. Inconsistent default value of dfs.datanode.stripedread.buffer.size. Contributed by Walter Su.
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/8e53311c
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/8e53311c
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/8e53311c
Branch: refs/heads/HDFS-8966
Commit: 8e53311ca20547cdd6658a77f3cdf05e6212855a
Parents: 8b73393
Author: Jing Zhao <ji...@apache.org>
Authored: Tue Oct 6 23:44:05 2015 -0700
Committer: Jing Zhao <ji...@apache.org>
Committed: Tue Oct 6 23:44:05 2015 -0700
----------------------------------------------------------------------
hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 3 +++
.../hadoop-hdfs/src/main/resources/hdfs-default.xml | 2 +-
2 files changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8e53311c/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index dcd4252..93d3ee7 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -814,6 +814,9 @@ Trunk (Unreleased)
HDFS-8557. Allow to configure RS and XOR raw coders (Kai Zheng)
+ HDFS-9206. Inconsistent default value of dfs.datanode.stripedread.buffer.size.
+ (Walter Su via jing9)
+
Release 2.8.0 - UNRELEASED
NEW FEATURES
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8e53311c/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml b/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
index 1475ecd..cff3e88 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
@@ -2454,7 +2454,7 @@
<property>
<name>dfs.datanode.stripedread.buffer.size</name>
- <value>262144</value>
+ <value>65536</value>
<description>Datanode striped read buffer size.
</description>
</property>
[33/35] hadoop git commit: Fixup CHANGES.txt to reflect recent
commits to 2.7.2 and 2.6.2
Posted by ji...@apache.org.
Fixup CHANGES.txt to reflect recent commits to 2.7.2 and 2.6.2
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/0841940a
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/0841940a
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/0841940a
Branch: refs/heads/HDFS-8966
Commit: 0841940a21737890e01731e66bc403786a78a922
Parents: 1107bd3
Author: Jason Lowe <jl...@apache.org>
Authored: Thu Oct 8 16:45:29 2015 +0000
Committer: Jason Lowe <jl...@apache.org>
Committed: Thu Oct 8 16:45:29 2015 +0000
----------------------------------------------------------------------
hadoop-yarn-project/CHANGES.txt | 39 +++++++++++++++++++++++++-----------
1 file changed, 27 insertions(+), 12 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/0841940a/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index d5e6920..c4d6ec9 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -705,9 +705,6 @@ Release 2.8.0 - UNRELEASED
YARN-3655. FairScheduler: potential livelock due to maxAMShare limitation
and container reservation. (Zhihai Xu via kasha)
- YARN-3780. Should use equals when compare Resource in RMNodeImpl#ReconnectNodeTransition.
- (zhihai xu via devaraj)
-
YARN-3747. TestLocalDirsHandlerService should delete the created test directory logDir2.
(David Moore via devaraj)
@@ -725,9 +722,6 @@ Release 2.8.0 - UNRELEASED
YARN-3824. Fix two minor nits in member variable properties
of YarnConfiguration. (Ray Chiang via devaraj)
- YARN-3802. Two RMNodes for the same NodeId are used in RM sometimes
- after NM is reconnected. (zhihai xu via xgong)
-
YARN-3835. hadoop-yarn-server-resourcemanager test package bundles
core-site.xml, yarn-site.xml (vamsee via rkanter)
@@ -856,9 +850,6 @@ Release 2.8.0 - UNRELEASED
YARN-3992. TestApplicationPriority.testApplicationPriorityAllocation fails
intermittently. (Contributed by Sunil G)
- YARN-4005. Completed container whose app is finished is possibly not
- removed from NMStateStore. (Jun Gong via jianhe)
-
YARN-3987. Send AM container completed msg to NM once AM finishes.
(sandflee via jianhe)
@@ -868,9 +859,6 @@ Release 2.8.0 - UNRELEASED
YARN-3986. getTransferredContainers in AbstractYarnScheduler should be present
in YarnScheduler interface instead. (Varun Saxena via rohithsharmaks)
- YARN-3896. RMNode transitioned from RUNNING to REBOOTED because its response id
- has not been reset synchronously. (Jun Gong via rohithsharmaks)
-
YARN-4082. Container shouldn't be killed when node's label updated.
(Wangda Tan via vvasudev)
@@ -1025,6 +1013,18 @@ Release 2.7.2 - UNRELEASED
YARN-4209. RMStateStore FENCED state doesn’t work due to updateFencedState called
by stateMachine.doTransition. (Zhihai Xu via rohithsharmaks)
+ YARN-4005. Completed container whose app is finished is possibly not
+ removed from NMStateStore. (Jun Gong via jianhe)
+
+ YARN-3780. Should use equals when compare Resource in RMNodeImpl#ReconnectNodeTransition.
+ (zhihai xu via devaraj)
+
+ YARN-3802. Two RMNodes for the same NodeId are used in RM sometimes
+ after NM is reconnected. (zhihai xu via xgong)
+
+ YARN-3896. RMNode transitioned from RUNNING to REBOOTED because its response id
+ has not been reset synchronously. (Jun Gong via rohithsharmaks)
+
Release 2.7.1 - 2015-07-06
INCOMPATIBLE CHANGES
@@ -1765,6 +1765,21 @@ Release 2.6.2 - UNRELEASED
BUG FIXES
+ YARN-4005. Completed container whose app is finished is possibly not
+ removed from NMStateStore. (Jun Gong via jianhe)
+
+ YARN-3780. Should use equals when compare Resource in RMNodeImpl#ReconnectNodeTransition.
+ (zhihai xu via devaraj)
+
+ YARN-3802. Two RMNodes for the same NodeId are used in RM sometimes
+ after NM is reconnected. (zhihai xu via xgong)
+
+ YARN-3194. RM should handle NMContainerStatuses sent by NM while
+ registering if NM is Reconnected node (Rohith via jlowe)
+
+ YARN-3896. RMNode transitioned from RUNNING to REBOOTED because its response id
+ has not been reset synchronously. (Jun Gong via rohithsharmaks)
+
Release 2.6.1 - 2015-09-23
INCOMPATIBLE CHANGES
[22/35] hadoop git commit: HDFS-9170. Move libhdfs / fuse-dfs /
libwebhdfs to hdfs-client. Contributed by Haohui Mai.
Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_ops.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_ops.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_ops.c
new file mode 100644
index 0000000..87550ae
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_ops.c
@@ -0,0 +1,552 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "hdfs.h"
+#include "native_mini_dfs.h"
+
+#include <inttypes.h>
+#include <jni.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+static struct NativeMiniDfsCluster *cluster;
+
+void permission_disp(short permissions, char *rtr)
+{
+ rtr[9] = '\0';
+ int i;
+ short perm;
+ for(i = 2; i >= 0; i--)
+ {
+ perm = permissions >> (i * 3);
+ rtr[0] = perm & 4 ? 'r' : '-';
+ rtr[1] = perm & 2 ? 'w' : '-';
+ rtr[2] = perm & 1 ? 'x' : '-';
+ rtr += 3;
+ }
+}
+
+int main(int argc, char **argv)
+{
+ char buffer[32];
+ tSize num_written_bytes;
+ const char* slashTmp = "/tmp";
+ int nnPort;
+ char *rwTemplate, *rwTemplate2, *newDirTemplate,
+ *appendTemplate, *userTemplate, *rwPath = NULL;
+ const char* fileContents = "Hello, World!";
+ const char* nnHost = NULL;
+
+ if (argc != 2) {
+ fprintf(stderr, "usage: test_libwebhdfs_ops <username>\n");
+ exit(1);
+ }
+
+ struct NativeMiniDfsConf conf = {
+ .doFormat = 1, .webhdfsEnabled = 1, .namenodeHttpPort = 50070,
+ };
+ cluster = nmdCreate(&conf);
+ if (!cluster) {
+ fprintf(stderr, "Failed to create the NativeMiniDfsCluster.\n");
+ exit(1);
+ }
+ if (nmdWaitClusterUp(cluster)) {
+ fprintf(stderr, "Error when waiting for cluster to be ready.\n");
+ exit(1);
+ }
+ if (nmdGetNameNodeHttpAddress(cluster, &nnPort, &nnHost)) {
+ fprintf(stderr, "Error when retrieving namenode host address.\n");
+ exit(1);
+ }
+
+ hdfsFS fs = hdfsConnectAsUserNewInstance(nnHost, nnPort, argv[1]);
+ if(!fs) {
+ fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
+ exit(-1);
+ }
+
+ {
+ // Write tests
+ rwTemplate = strdup("/tmp/helloWorldXXXXXX");
+ if (!rwTemplate) {
+ fprintf(stderr, "Failed to create rwTemplate!\n");
+ exit(1);
+ }
+ rwPath = mktemp(rwTemplate);
+ // hdfsOpenFile
+ hdfsFile writeFile = hdfsOpenFile(fs, rwPath,
+ O_WRONLY|O_CREAT, 0, 0, 0);
+
+ if(!writeFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", rwPath);
+ exit(1);
+ }
+ fprintf(stderr, "Opened %s for writing successfully...\n", rwPath);
+ // hdfsWrite
+ num_written_bytes = hdfsWrite(fs, writeFile, (void*)fileContents,
+ (int) strlen(fileContents) + 1);
+ if (num_written_bytes != strlen(fileContents) + 1) {
+ fprintf(stderr, "Failed to write correct number of bytes - "
+ "expected %d, got %d\n",
+ (int)(strlen(fileContents) + 1), (int) num_written_bytes);
+ exit(1);
+ }
+ fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
+
+ // hdfsTell
+ tOffset currentPos = -1;
+ if ((currentPos = hdfsTell(fs, writeFile)) == -1) {
+ fprintf(stderr,
+ "Failed to get current file position correctly. Got %"
+ PRId64 "!\n", currentPos);
+ exit(1);
+ }
+ fprintf(stderr, "Current position: %" PRId64 "\n", currentPos);
+
+ hdfsCloseFile(fs, writeFile);
+ // Done test write
+ }
+
+ sleep(1);
+
+ {
+ //Read tests
+ int available = 0, exists = 0;
+
+ // hdfsExists
+ exists = hdfsExists(fs, rwPath);
+ if (exists) {
+ fprintf(stderr, "Failed to validate existence of %s\n", rwPath);
+ exists = hdfsExists(fs, rwPath);
+ if (exists) {
+ fprintf(stderr,
+ "Still failed to validate existence of %s\n", rwPath);
+ exit(1);
+ }
+ }
+
+ hdfsFile readFile = hdfsOpenFile(fs, rwPath, O_RDONLY, 0, 0, 0);
+ if (!readFile) {
+ fprintf(stderr, "Failed to open %s for reading!\n", rwPath);
+ exit(1);
+ }
+ if (!hdfsFileIsOpenForRead(readFile)) {
+ fprintf(stderr, "hdfsFileIsOpenForRead: we just opened a file "
+ "with O_RDONLY, and it did not show up as 'open for "
+ "read'\n");
+ exit(1);
+ }
+
+ available = hdfsAvailable(fs, readFile);
+ fprintf(stderr, "hdfsAvailable: %d\n", available);
+
+ // hdfsSeek, hdfsTell
+ tOffset seekPos = 1;
+ if(hdfsSeek(fs, readFile, seekPos)) {
+ fprintf(stderr, "Failed to seek %s for reading!\n", rwPath);
+ exit(1);
+ }
+
+ tOffset currentPos = -1;
+ if((currentPos = hdfsTell(fs, readFile)) != seekPos) {
+ fprintf(stderr,
+ "Failed to get current file position correctly! Got %"
+ PRId64 "!\n", currentPos);
+
+ exit(1);
+ }
+ fprintf(stderr, "Current position: %" PRId64 "\n", currentPos);
+
+ if(hdfsSeek(fs, readFile, 0)) {
+ fprintf(stderr, "Failed to seek %s for reading!\n", rwPath);
+ exit(1);
+ }
+
+ // hdfsRead
+ memset(buffer, 0, sizeof(buffer));
+ tSize num_read_bytes = hdfsRead(fs, readFile, buffer, sizeof(buffer));
+ if (strncmp(fileContents, buffer, strlen(fileContents)) != 0) {
+ fprintf(stderr, "Failed to read (direct). "
+ "Expected %s but got %s (%d bytes)\n",
+ fileContents, buffer, num_read_bytes);
+ exit(1);
+ }
+ fprintf(stderr, "Read following %d bytes:\n%s\n",
+ num_read_bytes, buffer);
+
+ if (hdfsSeek(fs, readFile, 0L)) {
+ fprintf(stderr, "Failed to seek to file start!\n");
+ exit(1);
+ }
+
+ // hdfsPread
+ memset(buffer, 0, strlen(fileContents + 1));
+ num_read_bytes = hdfsPread(fs, readFile, 0, buffer, sizeof(buffer));
+ fprintf(stderr, "Read following %d bytes:\n%s\n",
+ num_read_bytes, buffer);
+
+ hdfsCloseFile(fs, readFile);
+ // Done test read
+ }
+
+ int totalResult = 0;
+ int result = 0;
+ {
+ //Generic file-system operations
+ char *srcPath = rwPath;
+ char buffer[256];
+ const char *resp;
+ rwTemplate2 = strdup("/tmp/helloWorld2XXXXXX");
+ if (!rwTemplate2) {
+ fprintf(stderr, "Failed to create rwTemplate2!\n");
+ exit(1);
+ }
+ char *dstPath = mktemp(rwTemplate2);
+ newDirTemplate = strdup("/tmp/newdirXXXXXX");
+ if (!newDirTemplate) {
+ fprintf(stderr, "Failed to create newDirTemplate!\n");
+ exit(1);
+ }
+ char *newDirectory = mktemp(newDirTemplate);
+
+ // hdfsRename
+ fprintf(stderr, "hdfsRename: %s\n",
+ ((result = hdfsRename(fs, rwPath, dstPath)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsRename back: %s\n",
+ ((result = hdfsRename(fs, dstPath, srcPath)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ // hdfsCreateDirectory
+ fprintf(stderr, "hdfsCreateDirectory: %s\n",
+ ((result = hdfsCreateDirectory(fs, newDirectory)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ // hdfsSetReplication
+ fprintf(stderr, "hdfsSetReplication: %s\n",
+ ((result = hdfsSetReplication(fs, srcPath, 1)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ // hdfsGetWorkingDirectory, hdfsSetWorkingDirectory
+ fprintf(stderr, "hdfsGetWorkingDirectory: %s\n",
+ ((resp = hdfsGetWorkingDirectory(fs, buffer, sizeof(buffer))) ?
+ buffer : "Failed!"));
+ totalResult += (resp ? 0 : 1);
+
+ const char* path[] = {"/foo", "/foo/bar", "foobar", "//foo/bar//foobar",
+ "foo//bar", "foo/bar///", "/", "////"};
+ int i;
+ for (i = 0; i < 8; i++) {
+ fprintf(stderr, "hdfsSetWorkingDirectory: %s, %s\n",
+ ((result = hdfsSetWorkingDirectory(fs, path[i])) ?
+ "Failed!" : "Success!"),
+ hdfsGetWorkingDirectory(fs, buffer, sizeof(buffer)));
+ totalResult += result;
+ }
+
+ fprintf(stderr, "hdfsSetWorkingDirectory: %s\n",
+ ((result = hdfsSetWorkingDirectory(fs, slashTmp)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsGetWorkingDirectory: %s\n",
+ ((resp = hdfsGetWorkingDirectory(fs, buffer, sizeof(buffer))) ?
+ buffer : "Failed!"));
+ totalResult += (resp ? 0 : 1);
+
+ // hdfsGetPathInfo
+ hdfsFileInfo *fileInfo = NULL;
+ if((fileInfo = hdfsGetPathInfo(fs, slashTmp)) != NULL) {
+ fprintf(stderr, "hdfsGetPathInfo - SUCCESS!\n");
+ fprintf(stderr, "Name: %s, ", fileInfo->mName);
+ fprintf(stderr, "Type: %c, ", (char)(fileInfo->mKind));
+ fprintf(stderr, "Replication: %d, ", fileInfo->mReplication);
+ fprintf(stderr, "BlockSize: %"PRId64", ", fileInfo->mBlockSize);
+ fprintf(stderr, "Size: %"PRId64", ", fileInfo->mSize);
+ fprintf(stderr, "LastMod: %s", ctime(&fileInfo->mLastMod));
+ fprintf(stderr, "Owner: %s, ", fileInfo->mOwner);
+ fprintf(stderr, "Group: %s, ", fileInfo->mGroup);
+ char permissions[10];
+ permission_disp(fileInfo->mPermissions, permissions);
+ fprintf(stderr, "Permissions: %d (%s)\n",
+ fileInfo->mPermissions, permissions);
+ hdfsFreeFileInfo(fileInfo, 1);
+ } else {
+ totalResult++;
+ fprintf(stderr, "hdfsGetPathInfo for %s - FAILED!\n", slashTmp);
+ }
+
+ // hdfsListDirectory
+ hdfsFileInfo *fileList = 0;
+ int numEntries = 0;
+ if((fileList = hdfsListDirectory(fs, slashTmp, &numEntries)) != NULL) {
+ int i = 0;
+ for(i=0; i < numEntries; ++i) {
+ fprintf(stderr, "Name: %s, ", fileList[i].mName);
+ fprintf(stderr, "Type: %c, ", (char)fileList[i].mKind);
+ fprintf(stderr, "Replication: %d, ", fileList[i].mReplication);
+ fprintf(stderr, "BlockSize: %"PRId64", ", fileList[i].mBlockSize);
+ fprintf(stderr, "Size: %"PRId64", ", fileList[i].mSize);
+ fprintf(stderr, "LastMod: %s", ctime(&fileList[i].mLastMod));
+ fprintf(stderr, "Owner: %s, ", fileList[i].mOwner);
+ fprintf(stderr, "Group: %s, ", fileList[i].mGroup);
+ char permissions[10];
+ permission_disp(fileList[i].mPermissions, permissions);
+ fprintf(stderr, "Permissions: %d (%s)\n",
+ fileList[i].mPermissions, permissions);
+ }
+ hdfsFreeFileInfo(fileList, numEntries);
+ } else {
+ if (errno) {
+ totalResult++;
+ fprintf(stderr, "waah! hdfsListDirectory - FAILED!\n");
+ } else {
+ fprintf(stderr, "Empty directory!\n");
+ }
+ }
+
+ char *newOwner = "root";
+ // Setting tmp dir to 777 so later when connectAsUser nobody,
+ // we can write to it
+ short newPerm = 0666;
+
+ // hdfsChown
+ fprintf(stderr, "hdfsChown: %s\n",
+ ((result = hdfsChown(fs, rwPath, NULL, "users")) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsChown: %s\n",
+ ((result = hdfsChown(fs, rwPath, newOwner, NULL)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+ // hdfsChmod
+ fprintf(stderr, "hdfsChmod: %s\n",
+ ((result = hdfsChmod(fs, rwPath, newPerm)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ sleep(2);
+ tTime newMtime = time(NULL);
+ tTime newAtime = time(NULL);
+
+ // utime write
+ fprintf(stderr, "hdfsUtime: %s\n",
+ ((result = hdfsUtime(fs, rwPath, newMtime, newAtime)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ // chown/chmod/utime read
+ hdfsFileInfo *finfo = hdfsGetPathInfo(fs, rwPath);
+
+ fprintf(stderr, "hdfsChown read: %s\n",
+ ((result = (strcmp(finfo->mOwner, newOwner) != 0)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ fprintf(stderr, "hdfsChmod read: %s\n",
+ ((result = (finfo->mPermissions != newPerm)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ // will later use /tmp/ as a different user so enable it
+ fprintf(stderr, "hdfsChmod: %s\n",
+ ((result = hdfsChmod(fs, slashTmp, 0777)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ fprintf(stderr,"newMTime=%ld\n",newMtime);
+ fprintf(stderr,"curMTime=%ld\n",finfo->mLastMod);
+
+
+ fprintf(stderr, "hdfsUtime read (mtime): %s\n",
+ ((result = (finfo->mLastMod != newMtime / 1000)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ // Clean up
+ hdfsFreeFileInfo(finfo, 1);
+ fprintf(stderr, "hdfsDelete: %s\n",
+ ((result = hdfsDelete(fs, newDirectory, 1)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsDelete: %s\n",
+ ((result = hdfsDelete(fs, srcPath, 1)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+ fprintf(stderr, "hdfsExists: %s\n",
+ ((result = hdfsExists(fs, newDirectory)) ?
+ "Success!" : "Failed!"));
+ totalResult += (result ? 0 : 1);
+ // Done test generic operations
+ }
+
+ {
+ // Test Appends
+ appendTemplate = strdup("/tmp/appendsXXXXXX");
+ if (!appendTemplate) {
+ fprintf(stderr, "Failed to create appendTemplate!\n");
+ exit(1);
+ }
+ char *appendPath = mktemp(appendTemplate);
+ const char* helloBuffer = "Hello,";
+ hdfsFile writeFile = NULL;
+
+ // Create
+ writeFile = hdfsOpenFile(fs, appendPath, O_WRONLY, 0, 0, 0);
+ if(!writeFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", appendPath);
+ exit(1);
+ }
+ fprintf(stderr, "Opened %s for writing successfully...\n", appendPath);
+
+ num_written_bytes = hdfsWrite(fs, writeFile, helloBuffer,
+ (int) strlen(helloBuffer));
+ fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
+ hdfsCloseFile(fs, writeFile);
+
+ fprintf(stderr, "hdfsSetReplication: %s\n",
+ ((result = hdfsSetReplication(fs, appendPath, 1)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+
+ // Re-Open for Append
+ writeFile = hdfsOpenFile(fs, appendPath, O_WRONLY | O_APPEND, 0, 0, 0);
+ if(!writeFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", appendPath);
+ exit(1);
+ }
+ fprintf(stderr, "Opened %s for appending successfully...\n",
+ appendPath);
+
+ helloBuffer = " World";
+ num_written_bytes = hdfsWrite(fs, writeFile, helloBuffer,
+ (int)strlen(helloBuffer) + 1);
+ fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
+
+ hdfsCloseFile(fs, writeFile);
+
+ // Check size
+ hdfsFileInfo *finfo = hdfsGetPathInfo(fs, appendPath);
+ fprintf(stderr, "fileinfo->mSize: == total %s\n",
+ ((result = (finfo->mSize == strlen("Hello, World") + 1)) ?
+ "Success!" : "Failed!"));
+ totalResult += (result ? 0 : 1);
+
+ // Read and check data
+ hdfsFile readFile = hdfsOpenFile(fs, appendPath, O_RDONLY, 0, 0, 0);
+ if (!readFile) {
+ fprintf(stderr, "Failed to open %s for reading!\n", appendPath);
+ exit(1);
+ }
+
+ tSize num_read_bytes = hdfsRead(fs, readFile, buffer, sizeof(buffer));
+ fprintf(stderr, "Read following %d bytes:\n%s\n",
+ num_read_bytes, buffer);
+ fprintf(stderr, "read == Hello, World %s\n",
+ (result = (strcmp(buffer, "Hello, World") == 0)) ?
+ "Success!" : "Failed!");
+ hdfsCloseFile(fs, readFile);
+
+ // Cleanup
+ fprintf(stderr, "hdfsDelete: %s\n",
+ ((result = hdfsDelete(fs, appendPath, 1)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+ // Done test appends
+ }
+
+ totalResult += (hdfsDisconnect(fs) != 0);
+
+ {
+ //
+ // Now test as connecting as a specific user
+ // This only meant to test that we connected as that user, not to test
+ // the actual fs user capabilities. Thus just create a file and read
+ // the owner is correct.
+ const char *tuser = "nobody";
+ userTemplate = strdup("/tmp/usertestXXXXXX");
+ if (!userTemplate) {
+ fprintf(stderr, "Failed to create userTemplate!\n");
+ exit(1);
+ }
+ char* userWritePath = mktemp(userTemplate);
+ hdfsFile writeFile = NULL;
+
+ fs = hdfsConnectAsUserNewInstance("default", 50070, tuser);
+ if(!fs) {
+ fprintf(stderr,
+ "Oops! Failed to connect to hdfs as user %s!\n",tuser);
+ exit(1);
+ }
+
+ writeFile = hdfsOpenFile(fs, userWritePath, O_WRONLY|O_CREAT, 0, 0, 0);
+ if(!writeFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", userWritePath);
+ exit(1);
+ }
+ fprintf(stderr, "Opened %s for writing successfully...\n",
+ userWritePath);
+
+ num_written_bytes = hdfsWrite(fs, writeFile, fileContents,
+ (int)strlen(fileContents) + 1);
+ fprintf(stderr, "Wrote %d bytes\n", num_written_bytes);
+ hdfsCloseFile(fs, writeFile);
+
+ hdfsFileInfo *finfo = hdfsGetPathInfo(fs, userWritePath);
+ if (finfo) {
+ fprintf(stderr, "hdfs new file user is correct: %s\n",
+ ((result = (strcmp(finfo->mOwner, tuser) != 0)) ?
+ "Failed!" : "Success!"));
+ } else {
+ fprintf(stderr,
+ "hdfsFileInfo returned by hdfsGetPathInfo is NULL\n");
+ result = -1;
+ }
+ totalResult += result;
+
+ // Cleanup
+ fprintf(stderr, "hdfsDelete: %s\n",
+ ((result = hdfsDelete(fs, userWritePath, 1)) ?
+ "Failed!" : "Success!"));
+ totalResult += result;
+ // Done test specific user
+ }
+
+ totalResult += (hdfsDisconnect(fs) != 0);
+
+ // Shutdown the native minidfscluster
+ nmdShutdown(cluster);
+ nmdFree(cluster);
+
+ fprintf(stderr, "totalResult == %d\n", totalResult);
+ if (totalResult != 0) {
+ return -1;
+ } else {
+ return 0;
+ }
+}
+
+/**
+ * vim: ts=4: sw=4: et:
+ */
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_read.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_read.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_read.c
new file mode 100644
index 0000000..4bd3078
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_read.c
@@ -0,0 +1,78 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "hdfs.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+int main(int argc, char **argv) {
+
+ const char* rfile;
+ tSize fileTotalSize, bufferSize, curSize, totalReadSize;
+ hdfsFS fs;
+ hdfsFile readFile;
+ char *buffer = NULL;
+
+ if (argc != 4) {
+ fprintf(stderr, "Usage: test_libwebhdfs_read"
+ " <filename> <filesize> <buffersize>\n");
+ exit(1);
+ }
+
+ fs = hdfsConnect("localhost", 50070);
+ if (!fs) {
+ fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
+ exit(1);
+ }
+
+ rfile = argv[1];
+ fileTotalSize = strtoul(argv[2], NULL, 10);
+ bufferSize = strtoul(argv[3], NULL, 10);
+
+ readFile = hdfsOpenFile(fs, rfile, O_RDONLY, bufferSize, 0, 0);
+ if (!readFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", rfile);
+ exit(1);
+ }
+
+ // data to be written to the file
+ buffer = malloc(sizeof(char) * bufferSize);
+ if(buffer == NULL) {
+ fprintf(stderr, "Failed to allocate buffer.\n");
+ exit(1);
+ }
+
+ // read from the file
+ curSize = bufferSize;
+ totalReadSize = 0;
+ for (; (curSize = hdfsRead(fs, readFile, buffer, bufferSize)) == bufferSize; ) {
+ totalReadSize += curSize;
+ }
+ totalReadSize += curSize;
+
+ fprintf(stderr, "size of the file: %d; reading size: %d\n",
+ fileTotalSize, totalReadSize);
+
+ free(buffer);
+ hdfsCloseFile(fs, readFile);
+ hdfsDisconnect(fs);
+
+ return 0;
+}
+
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_threaded.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_threaded.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_threaded.c
new file mode 100644
index 0000000..6c9a12e
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_threaded.c
@@ -0,0 +1,247 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "expect.h"
+#include "hdfs.h"
+#include "native_mini_dfs.h"
+
+#include <errno.h>
+#include <semaphore.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define TLH_MAX_THREADS 100
+
+static struct NativeMiniDfsCluster* cluster;
+
+static const char *user;
+
+struct tlhThreadInfo {
+ /** Thread index */
+ int threadIdx;
+ /** 0 = thread was successful; error code otherwise */
+ int success;
+ /** pthread identifier */
+ pthread_t thread;
+};
+
+static int hdfsSingleNameNodeConnect(struct NativeMiniDfsCluster *cluster,
+ hdfsFS *fs)
+{
+ int nnPort;
+ const char *nnHost;
+ hdfsFS hdfs;
+
+ if (nmdGetNameNodeHttpAddress(cluster, &nnPort, &nnHost)) {
+ fprintf(stderr, "Error when retrieving namenode host address.\n");
+ return 1;
+ }
+
+ hdfs = hdfsConnectAsUser(nnHost, nnPort, user);
+ if(!hdfs) {
+ fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
+ return 1;
+ }
+
+ *fs = hdfs;
+ return 0;
+}
+
+static int doTestHdfsOperations(struct tlhThreadInfo *ti, hdfsFS fs)
+{
+ char prefix[256], tmp[256];
+ hdfsFile file;
+ int ret, expected;
+ hdfsFileInfo *fileInfo;
+
+ snprintf(prefix, sizeof(prefix), "/tlhData%04d", ti->threadIdx);
+
+ if (hdfsExists(fs, prefix) == 0) {
+ EXPECT_ZERO(hdfsDelete(fs, prefix, 1));
+ }
+ EXPECT_ZERO(hdfsCreateDirectory(fs, prefix));
+ snprintf(tmp, sizeof(tmp), "%s/file", prefix);
+
+ EXPECT_NONNULL(hdfsOpenFile(fs, tmp, O_RDONLY, 0, 0, 0));
+
+ file = hdfsOpenFile(fs, tmp, O_WRONLY, 0, 0, 0);
+ EXPECT_NONNULL(file);
+
+ /* TODO: implement writeFully and use it here */
+ expected = (int)strlen(prefix);
+ ret = hdfsWrite(fs, file, prefix, expected);
+ if (ret < 0) {
+ ret = errno;
+ fprintf(stderr, "hdfsWrite failed and set errno %d\n", ret);
+ return ret;
+ }
+ if (ret != expected) {
+ fprintf(stderr, "hdfsWrite was supposed to write %d bytes, but "
+ "it wrote %d\n", ret, expected);
+ return EIO;
+ }
+ EXPECT_ZERO(hdfsFlush(fs, file));
+ EXPECT_ZERO(hdfsCloseFile(fs, file));
+
+ /* Let's re-open the file for reading */
+ file = hdfsOpenFile(fs, tmp, O_RDONLY, 0, 0, 0);
+ EXPECT_NONNULL(file);
+
+ /* TODO: implement readFully and use it here */
+ ret = hdfsRead(fs, file, tmp, sizeof(tmp));
+ if (ret < 0) {
+ ret = errno;
+ fprintf(stderr, "hdfsRead failed and set errno %d\n", ret);
+ return ret;
+ }
+ if (ret != expected) {
+ fprintf(stderr, "hdfsRead was supposed to read %d bytes, but "
+ "it read %d\n", ret, expected);
+ return EIO;
+ }
+ EXPECT_ZERO(memcmp(prefix, tmp, expected));
+ EXPECT_ZERO(hdfsCloseFile(fs, file));
+
+ snprintf(tmp, sizeof(tmp), "%s/file", prefix);
+ EXPECT_NONZERO(hdfsChown(fs, tmp, NULL, NULL));
+ EXPECT_ZERO(hdfsChown(fs, tmp, NULL, "doop"));
+ fileInfo = hdfsGetPathInfo(fs, tmp);
+ EXPECT_NONNULL(fileInfo);
+ EXPECT_ZERO(strcmp("doop", fileInfo->mGroup));
+ hdfsFreeFileInfo(fileInfo, 1);
+
+ EXPECT_ZERO(hdfsChown(fs, tmp, "ha", "doop2"));
+ fileInfo = hdfsGetPathInfo(fs, tmp);
+ EXPECT_NONNULL(fileInfo);
+ EXPECT_ZERO(strcmp("ha", fileInfo->mOwner));
+ EXPECT_ZERO(strcmp("doop2", fileInfo->mGroup));
+ hdfsFreeFileInfo(fileInfo, 1);
+
+ EXPECT_ZERO(hdfsChown(fs, tmp, "ha2", NULL));
+ fileInfo = hdfsGetPathInfo(fs, tmp);
+ EXPECT_NONNULL(fileInfo);
+ EXPECT_ZERO(strcmp("ha2", fileInfo->mOwner));
+ EXPECT_ZERO(strcmp("doop2", fileInfo->mGroup));
+ hdfsFreeFileInfo(fileInfo, 1);
+
+ EXPECT_ZERO(hdfsDelete(fs, prefix, 1));
+ return 0;
+}
+
+static void *testHdfsOperations(void *v)
+{
+ struct tlhThreadInfo *ti = (struct tlhThreadInfo*)v;
+ hdfsFS fs = NULL;
+ int ret;
+
+ fprintf(stderr, "testHdfsOperations(threadIdx=%d): starting\n",
+ ti->threadIdx);
+ ret = hdfsSingleNameNodeConnect(cluster, &fs);
+ if (ret) {
+ fprintf(stderr, "testHdfsOperations(threadIdx=%d): "
+ "hdfsSingleNameNodeConnect failed with error %d.\n",
+ ti->threadIdx, ret);
+ ti->success = EIO;
+ return NULL;
+ }
+ ti->success = doTestHdfsOperations(ti, fs);
+ if (hdfsDisconnect(fs)) {
+ ret = errno;
+ fprintf(stderr, "hdfsDisconnect error %d\n", ret);
+ ti->success = ret;
+ }
+ return NULL;
+}
+
+static int checkFailures(struct tlhThreadInfo *ti, int tlhNumThreads)
+{
+ int i, threadsFailed = 0;
+ const char *sep = "";
+
+ for (i = 0; i < tlhNumThreads; i++) {
+ if (ti[i].success != 0) {
+ threadsFailed = 1;
+ }
+ }
+ if (!threadsFailed) {
+ fprintf(stderr, "testLibHdfs: all threads succeeded. SUCCESS.\n");
+ return EXIT_SUCCESS;
+ }
+ fprintf(stderr, "testLibHdfs: some threads failed: [");
+ for (i = 0; i < tlhNumThreads; i++) {
+ if (ti[i].success != 0) {
+ fprintf(stderr, "%s%d", sep, i);
+ sep = ", ";
+ }
+ }
+ fprintf(stderr, "]. FAILURE.\n");
+ return EXIT_FAILURE;
+}
+
+/**
+ * Test that we can write a file with libhdfs and then read it back
+ */
+int main(int argc, const char *args[])
+{
+ int i, tlhNumThreads;
+ const char *tlhNumThreadsStr;
+ struct tlhThreadInfo ti[TLH_MAX_THREADS];
+
+ if (argc != 2) {
+ fprintf(stderr, "usage: test_libwebhdfs_threaded <username>\n");
+ exit(1);
+ }
+ user = args[1];
+
+ struct NativeMiniDfsConf conf = {
+ .doFormat = 1, .webhdfsEnabled = 1, .namenodeHttpPort = 50070,
+ };
+ cluster = nmdCreate(&conf);
+ EXPECT_NONNULL(cluster);
+ EXPECT_ZERO(nmdWaitClusterUp(cluster));
+
+ tlhNumThreadsStr = getenv("TLH_NUM_THREADS");
+ if (!tlhNumThreadsStr) {
+ tlhNumThreadsStr = "3";
+ }
+ tlhNumThreads = atoi(tlhNumThreadsStr);
+ if ((tlhNumThreads <= 0) || (tlhNumThreads > TLH_MAX_THREADS)) {
+ fprintf(stderr, "testLibHdfs: must have a number of threads "
+ "between 1 and %d inclusive, not %d\n",
+ TLH_MAX_THREADS, tlhNumThreads);
+ return EXIT_FAILURE;
+ }
+ memset(&ti[0], 0, sizeof(ti));
+ for (i = 0; i < tlhNumThreads; i++) {
+ ti[i].threadIdx = i;
+ }
+
+ for (i = 0; i < tlhNumThreads; i++) {
+ EXPECT_ZERO(pthread_create(&ti[i].thread, NULL,
+ testHdfsOperations, &ti[i]));
+ }
+ for (i = 0; i < tlhNumThreads; i++) {
+ EXPECT_ZERO(pthread_join(ti[i].thread, NULL));
+ }
+
+ EXPECT_ZERO(nmdShutdown(cluster));
+ nmdFree(cluster);
+ return checkFailures(ti, tlhNumThreads);
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_write.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_write.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_write.c
new file mode 100644
index 0000000..652fb86
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/contrib/libwebhdfs/src/test_libwebhdfs_write.c
@@ -0,0 +1,111 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "hdfs.h"
+
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+
+int main(int argc, char **argv) {
+ hdfsFS fs;
+ const char* writeFileName;
+ off_t fileTotalSize;
+ long long tmpBufferSize;
+ tSize bufferSize = 0, totalWriteSize = 0, toWrite = 0, written = 0;
+ hdfsFile writeFile = NULL;
+ int append, i = 0;
+ char* buffer = NULL;
+
+ if (argc != 6) {
+ fprintf(stderr, "Usage: test_libwebhdfs_write <filename> <filesize> "
+ "<buffersize> <username> <append>\n");
+ exit(1);
+ }
+
+ fs = hdfsConnectAsUser("default", 50070, argv[4]);
+ if (!fs) {
+ fprintf(stderr, "Oops! Failed to connect to hdfs!\n");
+ exit(1);
+ }
+
+ writeFileName = argv[1];
+ fileTotalSize = strtoul(argv[2], NULL, 10);
+ tmpBufferSize = strtoul(argv[3], NULL, 10);
+
+ // sanity check
+ if(fileTotalSize == ULONG_MAX && errno == ERANGE) {
+ fprintf(stderr, "invalid file size %s - must be <= %lu\n",
+ argv[2], ULONG_MAX);
+ exit(1);
+ }
+
+ // currently libhdfs writes are of tSize which is int32
+ if(tmpBufferSize > INT_MAX) {
+ fprintf(stderr,
+ "invalid buffer size libhdfs API write chunks must be <= %d\n",
+ INT_MAX);
+ exit(1);
+ }
+
+ bufferSize = (tSize) tmpBufferSize;
+ append = atoi(argv[5]);
+ if (!append) {
+ writeFile = hdfsOpenFile(fs, writeFileName, O_WRONLY, bufferSize, 2, 0);
+ } else {
+ writeFile = hdfsOpenFile(fs, writeFileName, O_WRONLY | O_APPEND,
+ bufferSize, 2, 0);
+ }
+ if (!writeFile) {
+ fprintf(stderr, "Failed to open %s for writing!\n", writeFileName);
+ exit(1);
+ }
+
+ // data to be written to the file
+ buffer = malloc(sizeof(char) * bufferSize + 1);
+ if(buffer == NULL) {
+ fprintf(stderr, "Could not allocate buffer of size %d\n", bufferSize);
+ exit(1);
+ }
+ for (i = 0; i < bufferSize; ++i) {
+ buffer[i] = 'a' + (i%26);
+ }
+ buffer[bufferSize] = '\0';
+
+ // write to the file
+ totalWriteSize = 0;
+ for (; totalWriteSize < fileTotalSize; ) {
+ toWrite = bufferSize < (fileTotalSize - totalWriteSize) ?
+ bufferSize : (fileTotalSize - totalWriteSize);
+ written = hdfsWrite(fs, writeFile, (void*)buffer, toWrite);
+ fprintf(stderr, "written size %d, to write size %d\n",
+ written, toWrite);
+ totalWriteSize += written;
+ }
+
+ // cleanup
+ free(buffer);
+ hdfsCloseFile(fs, writeFile);
+ fprintf(stderr, "file total size: %" PRId64 ", total write size: %d\n",
+ fileTotalSize, totalWriteSize);
+ hdfsDisconnect(fs);
+
+ return 0;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/CMakeLists.txt b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/CMakeLists.txt
new file mode 100644
index 0000000..0e0db5d
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/CMakeLists.txt
@@ -0,0 +1,88 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+#
+
+set(CMAKE_SKIP_RPATH TRUE)
+
+# Flatten a list into a string.
+function(flatten_list INPUT SEPARATOR OUTPUT)
+ string (REPLACE ";" "${SEPARATOR}" _TMPS "${INPUT}")
+ set (${OUTPUT} "${_TMPS}" PARENT_SCOPE)
+endfunction()
+
+flatten_list("${FUSE_CFLAGS}" " " FUSE_CFLAGS)
+flatten_list("${FUSE_LDFLAGS}" " " FUSE_LDFLAGS)
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${FUSE_CFLAGS}")
+set(CMAKE_LD_FLAGS "${CMAKE_LD_FLAGS} ${FUSE_LDFLAGS}")
+message(STATUS "Building Linux FUSE client.")
+
+include_directories(
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${JNI_INCLUDE_DIRS}
+ ${CMAKE_SOURCE_DIR}/main/native
+ ${CMAKE_SOURCE_DIR}/main/native/libhdfs
+ ${OS_DIR}
+ ${FUSE_INCLUDE_DIRS})
+
+add_executable(fuse_dfs
+ fuse_dfs.c
+ fuse_options.c
+ fuse_connect.c
+ fuse_impls_access.c
+ fuse_impls_chmod.c
+ fuse_impls_chown.c
+ fuse_impls_create.c
+ fuse_impls_flush.c
+ fuse_impls_getattr.c
+ fuse_impls_mkdir.c
+ fuse_impls_mknod.c
+ fuse_impls_open.c
+ fuse_impls_read.c
+ fuse_impls_readdir.c
+ fuse_impls_release.c
+ fuse_impls_rename.c
+ fuse_impls_rmdir.c
+ fuse_impls_statfs.c
+ fuse_impls_symlink.c
+ fuse_impls_truncate.c
+ fuse_impls_unlink.c
+ fuse_impls_utimens.c
+ fuse_impls_write.c
+ fuse_init.c
+ fuse_stat_struct.c
+ fuse_trash.c
+ fuse_users.c
+)
+target_link_libraries(fuse_dfs
+ ${FUSE_LIBRARIES}
+ ${JAVA_JVM_LIBRARY}
+ hdfs
+ m
+ pthread
+ rt
+)
+add_executable(test_fuse_dfs
+ test/test_fuse_dfs.c
+ test/fuse_workload.c
+ util/posix_util.c
+)
+target_link_libraries(test_fuse_dfs
+ ${FUSE_LIBRARIES}
+ native_mini_dfs
+ pthread
+)
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/doc/README
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/doc/README b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/doc/README
new file mode 100644
index 0000000..1744892
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/doc/README
@@ -0,0 +1,131 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+Fuse-DFS
+
+Supports reads, writes, and directory operations (e.g., cp, ls, more, cat, find, less, rm, mkdir, mv, rmdir). Things like touch, chmod, chown, and permissions are in the works. Fuse-dfs currently shows all files as owned by nobody.
+
+Contributing
+
+It's pretty straightforward to add functionality to fuse-dfs as fuse makes things relatively simple. Some other tasks require also augmenting libhdfs to expose more hdfs functionality to C. See [http://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&mode=hide&pid=12310240&sorter/order=DESC&sorter/field=priority&resolution=-1&component=12312376 contrib/fuse-dfs JIRAs]
+
+Requirements
+
+ * Hadoop with compiled libhdfs.so
+ * Linux kernel > 2.6.9 with fuse, which is the default or Fuse 2.7.x, 2.8.x installed. See: [http://fuse.sourceforge.net/]
+ * modprobe fuse to load it
+ * fuse-dfs executable (see below)
+ * fuse_dfs_wrapper.sh installed in /bin or other appropriate location (see below)
+
+
+BUILDING
+
+ 1. in HADOOP_PREFIX: `ant compile-libhdfs -Dlibhdfs=1
+ 2. in HADOOP_PREFIX: `ant package` to deploy libhdfs
+ 3. in HADOOP_PREFIX: `ant compile-contrib -Dlibhdfs=1 -Dfusedfs=1`
+
+NOTE: for amd64 architecture, libhdfs will not compile unless you edit
+the Makefile in src/c++/libhdfs/Makefile and set OS_ARCH=amd64
+(probably the same for others too). See [https://issues.apache.org/jira/browse/HADOOP-3344 HADOOP-3344]
+
+Common build problems include not finding the libjvm.so in JAVA_HOME/jre/lib/OS_ARCH/server or not finding fuse in FUSE_HOME or /usr/local.
+
+
+CONFIGURING
+
+Look at all the paths in fuse_dfs_wrapper.sh and either correct them or set them in your environment before running. (note for automount and mount as root, you probably cannot control the environment, so best to set them in the wrapper)
+
+INSTALLING
+
+1. `mkdir /export/hdfs` (or wherever you want to mount it)
+
+2. `fuse_dfs_wrapper.sh dfs://hadoop_server1.foo.com:9000 /export/hdfs -d` and from another terminal, try `ls /export/hdfs`
+
+If 2 works, try again dropping the debug mode, i.e., -d
+
+(note - common problems are that you don't have libhdfs.so or libjvm.so or libfuse.so on your LD_LIBRARY_PATH, and your CLASSPATH does not contain hadoop and other required jars.)
+
+Also note, fuse-dfs will write error/warn messages to the syslog - typically in /var/log/messages
+
+You can use fuse-dfs to mount multiple hdfs instances by just changing the server/port name and directory mount point above.
+
+DEPLOYING
+
+in a root shell do the following:
+
+1. add the following to /etc/fstab
+
+fuse_dfs#dfs://hadoop_server.foo.com:9000 /export/hdfs fuse -oallow_other,rw,-ousetrash,-oinitchecks 0 0
+
+
+2. Mount using: `mount /export/hdfs`. Expect problems with not finding fuse_dfs. You will need to probably add this to /sbin and then problems finding the above 3 libraries. Add these using ldconfig.
+
+
+Fuse DFS takes the following mount options (i.e., on the command line or the comma separated list of options in /etc/fstab:
+
+-oserver=%s (optional place to specify the server but in fstab use the format above)
+-oport=%d (optional port see comment on server option)
+-oentry_timeout=%d (how long directory entries are cached by fuse in seconds - see fuse docs)
+-oattribute_timeout=%d (how long attributes are cached by fuse in seconds - see fuse docs)
+-oprotected=%s (a colon separated list of directories that fuse-dfs should not allow to be deleted or moved - e.g., /user:/tmp)
+-oprivate (not often used but means only the person who does the mount can use the filesystem - aka ! allow_others in fuse speak)
+-ordbuffer=%d (in KBs how large a buffer should fuse-dfs use when doing hdfs reads)
+ro
+rw
+-ousetrash (should fuse dfs throw things in /Trash when deleting them)
+-onotrash (opposite of usetrash)
+-odebug (do not daemonize - aka -d in fuse speak)
+-obig_writes (use fuse big_writes option so as to allow better performance of writes on kernels >= 2.6.26)
+-initchecks - have fuse-dfs try to connect to hdfs to ensure all is ok upon startup. recommended to have this on
+The defaults are:
+
+entry,attribute_timeouts = 60 seconds
+rdbuffer = 10 MB
+protected = null
+debug = 0
+notrash
+private = 0
+
+EXPORTING
+
+Add the following to /etc/exports:
+
+/export/hdfs *.foo.com(no_root_squash,rw,fsid=1,sync)
+
+NOTE - you cannot export this with a FUSE module built into the kernel
+- e.g., kernel 2.6.17. For info on this, refer to the FUSE wiki.
+
+
+RECOMMENDATIONS
+
+1. From /bin, `ln -s $HADOOP_PREFIX/contrib/fuse-dfs/fuse_dfs* .`
+
+2. Always start with debug on so you can see if you are missing a classpath or something like that.
+
+3. use -obig_writes
+
+4. use -initchecks
+
+KNOWN ISSUES
+
+1. if you alias `ls` to `ls --color=auto` and try listing a directory with lots (over thousands) of files, expect it to be slow and at 10s of thousands, expect it to be very very slow. This is because `--color=auto` causes ls to stat every file in the directory. Since fuse-dfs does not cache attribute entries when doing a readdir,
+this is very slow. see [https://issues.apache.org/jira/browse/HADOOP-3797 HADOOP-3797]
+
+2. Writes are approximately 33% slower than the DFSClient. TBD how to optimize this. see: [https://issues.apache.org/jira/browse/HADOOP-3805 HADOOP-3805] - try using -obig_writes if on a >2.6.26 kernel, should perform much better since bigger writes implies less context switching.
+
+3. Reads are ~20-30% slower even with the read buffering.
+
+4. fuse-dfs and underlying libhdfs have no support for permissions. See [https://issues.apache.org/jira/browse/HADOOP-3536 HADOOP-3536]
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_connect.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_connect.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_connect.c
new file mode 100644
index 0000000..8a2a00b
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_connect.c
@@ -0,0 +1,644 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_connect.h"
+#include "fuse_dfs.h"
+#include "fuse_users.h"
+#include "libhdfs/hdfs.h"
+#include "util/tree.h"
+
+#include <inttypes.h>
+#include <limits.h>
+#include <poll.h>
+#include <search.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <utime.h>
+
+#define FUSE_CONN_DEFAULT_TIMER_PERIOD 5
+#define FUSE_CONN_DEFAULT_EXPIRY_PERIOD (5 * 60)
+#define HADOOP_SECURITY_AUTHENTICATION "hadoop.security.authentication"
+#define HADOOP_FUSE_CONNECTION_TIMEOUT "hadoop.fuse.connection.timeout"
+#define HADOOP_FUSE_TIMER_PERIOD "hadoop.fuse.timer.period"
+
+/** Length of the buffer needed by asctime_r */
+#define TIME_STR_LEN 26
+
+struct hdfsConn;
+
+static int hdfsConnCompare(const struct hdfsConn *a, const struct hdfsConn *b);
+static void hdfsConnExpiry(void);
+static void* hdfsConnExpiryThread(void *v);
+
+RB_HEAD(hdfsConnTree, hdfsConn);
+
+enum authConf {
+ AUTH_CONF_UNKNOWN,
+ AUTH_CONF_KERBEROS,
+ AUTH_CONF_OTHER,
+};
+
+struct hdfsConn {
+ RB_ENTRY(hdfsConn) entry;
+ /** How many threads are currently using this hdfsConnection object */
+ int64_t refcnt;
+ /** The username used to make this connection. Dynamically allocated. */
+ char *usrname;
+ /** Kerberos ticket cache path, or NULL if this is not a kerberized
+ * connection. Dynamically allocated. */
+ char *kpath;
+ /** mtime of the kpath, if the kpath is non-NULL */
+ time_t kPathMtime;
+ /** nanosecond component of the mtime of the kpath, if the kpath is non-NULL */
+ long kPathMtimeNs;
+ /** The cached libhdfs fs instance */
+ hdfsFS fs;
+ /** Nonzero if this hdfs connection needs to be closed as soon as possible.
+ * If this is true, the connection has been removed from the tree. */
+ int condemned;
+ /** Number of times we should run the expiration timer on this connection
+ * before removing it. */
+ int expirationCount;
+};
+
+RB_GENERATE(hdfsConnTree, hdfsConn, entry, hdfsConnCompare);
+
+/** Current cached libhdfs connections */
+static struct hdfsConnTree gConnTree;
+
+/** The URI used to make our connections. Dynamically allocated. */
+static char *gUri;
+
+/** The port used to make our connections, or 0. */
+static int gPort;
+
+/** Lock which protects gConnTree and gConnectTimer->active */
+static pthread_mutex_t gConnMutex;
+
+/** Type of authentication configured */
+static enum authConf gHdfsAuthConf;
+
+/** FUSE connection timer expiration period */
+static int32_t gTimerPeriod;
+
+/** FUSE connection expiry period */
+static int32_t gExpiryPeriod;
+
+/** FUSE timer expiration thread */
+static pthread_t gTimerThread;
+
+/**
+ * Find out what type of authentication the system administrator
+ * has configured.
+ *
+ * @return the type of authentication, or AUTH_CONF_UNKNOWN on error.
+ */
+static enum authConf discoverAuthConf(void)
+{
+ int ret;
+ char *val = NULL;
+ enum authConf authConf;
+
+ ret = hdfsConfGetStr(HADOOP_SECURITY_AUTHENTICATION, &val);
+ if (ret)
+ authConf = AUTH_CONF_UNKNOWN;
+ else if (!val)
+ authConf = AUTH_CONF_OTHER;
+ else if (!strcmp(val, "kerberos"))
+ authConf = AUTH_CONF_KERBEROS;
+ else
+ authConf = AUTH_CONF_OTHER;
+ free(val);
+ return authConf;
+}
+
+int fuseConnectInit(const char *nnUri, int port)
+{
+ int ret;
+
+ gTimerPeriod = FUSE_CONN_DEFAULT_TIMER_PERIOD;
+ ret = hdfsConfGetInt(HADOOP_FUSE_TIMER_PERIOD, &gTimerPeriod);
+ if (ret) {
+ fprintf(stderr, "Unable to determine the configured value for %s.",
+ HADOOP_FUSE_TIMER_PERIOD);
+ return -EINVAL;
+ }
+ if (gTimerPeriod < 1) {
+ fprintf(stderr, "Invalid value %d given for %s.\n",
+ gTimerPeriod, HADOOP_FUSE_TIMER_PERIOD);
+ return -EINVAL;
+ }
+ gExpiryPeriod = FUSE_CONN_DEFAULT_EXPIRY_PERIOD;
+ ret = hdfsConfGetInt(HADOOP_FUSE_CONNECTION_TIMEOUT, &gExpiryPeriod);
+ if (ret) {
+ fprintf(stderr, "Unable to determine the configured value for %s.",
+ HADOOP_FUSE_CONNECTION_TIMEOUT);
+ return -EINVAL;
+ }
+ if (gExpiryPeriod < 1) {
+ fprintf(stderr, "Invalid value %d given for %s.\n",
+ gExpiryPeriod, HADOOP_FUSE_CONNECTION_TIMEOUT);
+ return -EINVAL;
+ }
+ gHdfsAuthConf = discoverAuthConf();
+ if (gHdfsAuthConf == AUTH_CONF_UNKNOWN) {
+ fprintf(stderr, "Unable to determine the configured value for %s.",
+ HADOOP_SECURITY_AUTHENTICATION);
+ return -EINVAL;
+ }
+ gPort = port;
+ gUri = strdup(nnUri);
+ if (!gUri) {
+ fprintf(stderr, "fuseConnectInit: OOM allocting nnUri\n");
+ return -ENOMEM;
+ }
+ ret = pthread_mutex_init(&gConnMutex, NULL);
+ if (ret) {
+ free(gUri);
+ fprintf(stderr, "fuseConnectInit: pthread_mutex_init failed with error %d\n",
+ ret);
+ return -ret;
+ }
+ RB_INIT(&gConnTree);
+ ret = pthread_create(&gTimerThread, NULL, hdfsConnExpiryThread, NULL);
+ if (ret) {
+ free(gUri);
+ pthread_mutex_destroy(&gConnMutex);
+ fprintf(stderr, "fuseConnectInit: pthread_create failed with error %d\n",
+ ret);
+ return -ret;
+ }
+ fprintf(stderr, "fuseConnectInit: initialized with timer period %d, "
+ "expiry period %d\n", gTimerPeriod, gExpiryPeriod);
+ return 0;
+}
+
+/**
+ * Compare two libhdfs connections by username
+ *
+ * @param a The first libhdfs connection
+ * @param b The second libhdfs connection
+ *
+ * @return -1, 0, or 1 depending on a < b, a ==b, a > b
+ */
+static int hdfsConnCompare(const struct hdfsConn *a, const struct hdfsConn *b)
+{
+ return strcmp(a->usrname, b->usrname);
+}
+
+/**
+ * Find a libhdfs connection by username
+ *
+ * @param usrname The username to look up
+ *
+ * @return The connection, or NULL if none could be found
+ */
+static struct hdfsConn* hdfsConnFind(const char *usrname)
+{
+ struct hdfsConn exemplar;
+
+ memset(&exemplar, 0, sizeof(exemplar));
+ exemplar.usrname = (char*)usrname;
+ return RB_FIND(hdfsConnTree, &gConnTree, &exemplar);
+}
+
+/**
+ * Free the resource associated with a libhdfs connection.
+ *
+ * You must remove the connection from the tree before calling this function.
+ *
+ * @param conn The libhdfs connection
+ */
+static void hdfsConnFree(struct hdfsConn *conn)
+{
+ int ret;
+
+ ret = hdfsDisconnect(conn->fs);
+ if (ret) {
+ fprintf(stderr, "hdfsConnFree(username=%s): "
+ "hdfsDisconnect failed with error %d\n",
+ (conn->usrname ? conn->usrname : "(null)"), ret);
+ }
+ free(conn->usrname);
+ free(conn->kpath);
+ free(conn);
+}
+
+/**
+ * Convert a time_t to a string.
+ *
+ * @param sec time in seconds since the epoch
+ * @param buf (out param) output buffer
+ * @param bufLen length of output buffer
+ *
+ * @return 0 on success; ENAMETOOLONG if the provided buffer was
+ * too short
+ */
+static int timeToStr(time_t sec, char *buf, size_t bufLen)
+{
+ struct tm tm, *out;
+ size_t l;
+
+ if (bufLen < TIME_STR_LEN) {
+ return -ENAMETOOLONG;
+ }
+ out = localtime_r(&sec, &tm);
+ asctime_r(out, buf);
+ // strip trailing newline
+ l = strlen(buf);
+ if (l != 0)
+ buf[l - 1] = '\0';
+ return 0;
+}
+
+/**
+ * Check an HDFS connection's Kerberos path.
+ *
+ * If the mtime of the Kerberos ticket cache file has changed since we first
+ * opened the connection, mark the connection as condemned and remove it from
+ * the hdfs connection tree.
+ *
+ * @param conn The HDFS connection
+ */
+static int hdfsConnCheckKpath(const struct hdfsConn *conn)
+{
+ int ret;
+ struct stat st;
+ char prevTimeBuf[TIME_STR_LEN], newTimeBuf[TIME_STR_LEN];
+
+ if (stat(conn->kpath, &st) < 0) {
+ ret = errno;
+ if (ret == ENOENT) {
+ fprintf(stderr, "hdfsConnCheckKpath(conn.usrname=%s): the kerberos "
+ "ticket cache file '%s' has disappeared. Condemning the "
+ "connection.\n", conn->usrname, conn->kpath);
+ } else {
+ fprintf(stderr, "hdfsConnCheckKpath(conn.usrname=%s): stat(%s) "
+ "failed with error code %d. Pessimistically condemning the "
+ "connection.\n", conn->usrname, conn->kpath, ret);
+ }
+ return -ret;
+ }
+ if ((st.st_mtim.tv_sec != conn->kPathMtime) ||
+ (st.st_mtim.tv_nsec != conn->kPathMtimeNs)) {
+ timeToStr(conn->kPathMtime, prevTimeBuf, sizeof(prevTimeBuf));
+ timeToStr(st.st_mtim.tv_sec, newTimeBuf, sizeof(newTimeBuf));
+ fprintf(stderr, "hdfsConnCheckKpath(conn.usrname=%s): mtime on '%s' "
+ "has changed from '%s' to '%s'. Condemning the connection "
+ "because our cached Kerberos credentials have probably "
+ "changed.\n", conn->usrname, conn->kpath, prevTimeBuf, newTimeBuf);
+ return -EINTERNAL;
+ }
+ return 0;
+}
+
+/**
+ * Cache expiration logic.
+ *
+ * This function is called periodically by the cache expiration thread. For
+ * each FUSE connection not currently in use (refcnt == 0) it will decrement the
+ * expirationCount for that connection. Once the expirationCount reaches 0 for
+ * a connection, it can be garbage collected.
+ *
+ * We also check to see if the Kerberos credentials have changed. If so, the
+ * connecton is immediately condemned, even if it is currently in use.
+ */
+static void hdfsConnExpiry(void)
+{
+ struct hdfsConn *conn, *tmpConn;
+
+ pthread_mutex_lock(&gConnMutex);
+ RB_FOREACH_SAFE(conn, hdfsConnTree, &gConnTree, tmpConn) {
+ if (conn->kpath) {
+ if (hdfsConnCheckKpath(conn)) {
+ conn->condemned = 1;
+ RB_REMOVE(hdfsConnTree, &gConnTree, conn);
+ if (conn->refcnt == 0) {
+ /* If the connection is not in use by any threads, delete it
+ * immediately. If it is still in use by some threads, the last
+ * thread using it will clean it up later inside hdfsConnRelease. */
+ hdfsConnFree(conn);
+ continue;
+ }
+ }
+ }
+ if (conn->refcnt == 0) {
+ /* If the connection is not currently in use by a thread, check to see if
+ * it ought to be removed because it's too old. */
+ conn->expirationCount--;
+ if (conn->expirationCount <= 0) {
+ if (conn->condemned) {
+ fprintf(stderr, "hdfsConnExpiry: LOGIC ERROR: condemned connection "
+ "as %s is still in the tree!\n", conn->usrname);
+ }
+ fprintf(stderr, "hdfsConnExpiry: freeing and removing connection as "
+ "%s because it's now too old.\n", conn->usrname);
+ RB_REMOVE(hdfsConnTree, &gConnTree, conn);
+ hdfsConnFree(conn);
+ }
+ }
+ }
+ pthread_mutex_unlock(&gConnMutex);
+}
+
+// The Kerberos FILE: prefix. This indicates that the kerberos ticket cache
+// specifier is a file. (Note that we also assume that the specifier is a file
+// if no prefix is present.)
+#define KRB_FILE_PREFIX "FILE:"
+
+// Length of the Kerberos file prefix, which is equal to the string size in
+// bytes minus 1 (because we don't count the null terminator in the length.)
+#define KRB_FILE_PREFIX_LEN (sizeof(KRB_FILE_PREFIX) - 1)
+
+/**
+ * Find the Kerberos ticket cache path.
+ *
+ * This function finds the Kerberos ticket cache path from the thread ID and
+ * user ID of the process making the request.
+ *
+ * Normally, the ticket cache path is in a well-known location in /tmp.
+ * However, it's possible that the calling process could set the KRB5CCNAME
+ * environment variable, indicating that its Kerberos ticket cache is at a
+ * non-default location. We try to handle this possibility by reading the
+ * process' environment here. This will be allowed if we have root
+ * capabilities, or if our UID is the same as the remote process' UID.
+ *
+ * Note that we don't check to see if the cache file actually exists or not.
+ * We're just trying to find out where it would be if it did exist.
+ *
+ * @param path (out param) the path to the ticket cache file
+ * @param pathLen length of the path buffer
+ */
+static void findKerbTicketCachePath(struct fuse_context *ctx,
+ char *path, size_t pathLen)
+{
+ FILE *fp = NULL;
+ static const char * const KRB5CCNAME = "\0KRB5CCNAME=";
+ int c = '\0', pathIdx = 0, keyIdx = 0;
+ size_t KRB5CCNAME_LEN = strlen(KRB5CCNAME + 1) + 1;
+
+ // /proc/<tid>/environ contains the remote process' environment. It is
+ // exposed to us as a series of KEY=VALUE pairs, separated by NULL bytes.
+ snprintf(path, pathLen, "/proc/%d/environ", ctx->pid);
+ fp = fopen(path, "r");
+ if (!fp)
+ goto done;
+ while (1) {
+ if (c == EOF)
+ goto done;
+ if (keyIdx == KRB5CCNAME_LEN) {
+ if (pathIdx >= pathLen - 1)
+ goto done;
+ if (c == '\0')
+ goto done;
+ path[pathIdx++] = c;
+ } else if (KRB5CCNAME[keyIdx++] != c) {
+ keyIdx = 0;
+ }
+ c = fgetc(fp);
+ }
+
+done:
+ if (fp)
+ fclose(fp);
+ if (pathIdx == 0) {
+ snprintf(path, pathLen, "/tmp/krb5cc_%d", ctx->uid);
+ } else {
+ path[pathIdx] = '\0';
+ }
+ if (strncmp(path, KRB_FILE_PREFIX, KRB_FILE_PREFIX_LEN) == 0) {
+ fprintf(stderr, "stripping " KRB_FILE_PREFIX " from the front of "
+ "KRB5CCNAME.\n");
+ memmove(path, path + KRB_FILE_PREFIX_LEN,
+ strlen(path + KRB_FILE_PREFIX_LEN) + 1);
+ }
+}
+
+/**
+ * Create a new libhdfs connection.
+ *
+ * @param usrname Username to use for the new connection
+ * @param ctx FUSE context to use for the new connection
+ * @param out (out param) the new libhdfs connection
+ *
+ * @return 0 on success; error code otherwise
+ */
+static int fuseNewConnect(const char *usrname, struct fuse_context *ctx,
+ struct hdfsConn **out)
+{
+ struct hdfsBuilder *bld = NULL;
+ char kpath[PATH_MAX] = { 0 };
+ struct hdfsConn *conn = NULL;
+ int ret;
+ struct stat st;
+
+ conn = calloc(1, sizeof(struct hdfsConn));
+ if (!conn) {
+ fprintf(stderr, "fuseNewConnect: OOM allocating struct hdfsConn\n");
+ ret = -ENOMEM;
+ goto error;
+ }
+ bld = hdfsNewBuilder();
+ if (!bld) {
+ fprintf(stderr, "Unable to create hdfs builder\n");
+ ret = -ENOMEM;
+ goto error;
+ }
+ /* We always want to get a new FileSystem instance here-- that's why we call
+ * hdfsBuilderSetForceNewInstance. Otherwise the 'cache condemnation' logic
+ * in hdfsConnExpiry will not work correctly, since FileSystem might re-use the
+ * existing cached connection which we wanted to get rid of.
+ */
+ hdfsBuilderSetForceNewInstance(bld);
+ hdfsBuilderSetNameNode(bld, gUri);
+ if (gPort) {
+ hdfsBuilderSetNameNodePort(bld, gPort);
+ }
+ hdfsBuilderSetUserName(bld, usrname);
+ if (gHdfsAuthConf == AUTH_CONF_KERBEROS) {
+ findKerbTicketCachePath(ctx, kpath, sizeof(kpath));
+ if (stat(kpath, &st) < 0) {
+ fprintf(stderr, "fuseNewConnect: failed to find Kerberos ticket cache "
+ "file '%s'. Did you remember to kinit for UID %d?\n",
+ kpath, ctx->uid);
+ ret = -EACCES;
+ goto error;
+ }
+ conn->kPathMtime = st.st_mtim.tv_sec;
+ conn->kPathMtimeNs = st.st_mtim.tv_nsec;
+ hdfsBuilderSetKerbTicketCachePath(bld, kpath);
+ conn->kpath = strdup(kpath);
+ if (!conn->kpath) {
+ fprintf(stderr, "fuseNewConnect: OOM allocating kpath\n");
+ ret = -ENOMEM;
+ goto error;
+ }
+ }
+ conn->usrname = strdup(usrname);
+ if (!conn->usrname) {
+ fprintf(stderr, "fuseNewConnect: OOM allocating usrname\n");
+ ret = -ENOMEM;
+ goto error;
+ }
+ conn->fs = hdfsBuilderConnect(bld);
+ bld = NULL;
+ if (!conn->fs) {
+ ret = errno;
+ fprintf(stderr, "fuseNewConnect(usrname=%s): Unable to create fs: "
+ "error code %d\n", usrname, ret);
+ goto error;
+ }
+ RB_INSERT(hdfsConnTree, &gConnTree, conn);
+ *out = conn;
+ return 0;
+
+error:
+ if (bld) {
+ hdfsFreeBuilder(bld);
+ }
+ if (conn) {
+ free(conn->kpath);
+ free(conn->usrname);
+ free(conn);
+ }
+ return ret;
+}
+
+int fuseConnect(const char *usrname, struct fuse_context *ctx,
+ struct hdfsConn **out)
+{
+ int ret;
+ struct hdfsConn* conn;
+
+ pthread_mutex_lock(&gConnMutex);
+ conn = hdfsConnFind(usrname);
+ if (!conn) {
+ ret = fuseNewConnect(usrname, ctx, &conn);
+ if (ret) {
+ pthread_mutex_unlock(&gConnMutex);
+ fprintf(stderr, "fuseConnect(usrname=%s): fuseNewConnect failed with "
+ "error code %d\n", usrname, ret);
+ return ret;
+ }
+ }
+ conn->refcnt++;
+ conn->expirationCount = (gExpiryPeriod + gTimerPeriod - 1) / gTimerPeriod;
+ if (conn->expirationCount < 2)
+ conn->expirationCount = 2;
+ pthread_mutex_unlock(&gConnMutex);
+ *out = conn;
+ return 0;
+}
+
+int fuseConnectAsThreadUid(struct hdfsConn **conn)
+{
+ struct fuse_context *ctx;
+ char *usrname;
+ int ret;
+
+ ctx = fuse_get_context();
+ usrname = getUsername(ctx->uid);
+ ret = fuseConnect(usrname, ctx, conn);
+ free(usrname);
+ return ret;
+}
+
+int fuseConnectTest(void)
+{
+ int ret;
+ struct hdfsConn *conn;
+
+ if (gHdfsAuthConf == AUTH_CONF_KERBEROS) {
+ // TODO: call some method which can tell us whether the FS exists. In order
+ // to implement this, we have to add a method to FileSystem in order to do
+ // this without valid Kerberos authentication. See HDFS-3674 for details.
+ return 0;
+ }
+ ret = fuseNewConnect("root", NULL, &conn);
+ if (ret) {
+ fprintf(stderr, "fuseConnectTest failed with error code %d\n", ret);
+ return ret;
+ }
+ hdfsConnRelease(conn);
+ return 0;
+}
+
+struct hdfs_internal* hdfsConnGetFs(struct hdfsConn *conn)
+{
+ return conn->fs;
+}
+
+void hdfsConnRelease(struct hdfsConn *conn)
+{
+ pthread_mutex_lock(&gConnMutex);
+ conn->refcnt--;
+ if ((conn->refcnt == 0) && (conn->condemned)) {
+ fprintf(stderr, "hdfsConnRelease(usrname=%s): freeing condemend FS!\n",
+ conn->usrname);
+ /* Notice that we're not removing the connection from gConnTree here.
+ * If the connection is condemned, it must have already been removed from
+ * the tree, so that no other threads start using it.
+ */
+ hdfsConnFree(conn);
+ }
+ pthread_mutex_unlock(&gConnMutex);
+}
+
+/**
+ * Get the monotonic time.
+ *
+ * Unlike the wall-clock time, monotonic time only ever goes forward. If the
+ * user adjusts the time, the monotonic time will not be affected.
+ *
+ * @return The monotonic time
+ */
+static time_t getMonotonicTime(void)
+{
+ int res;
+ struct timespec ts;
+
+ res = clock_gettime(CLOCK_MONOTONIC, &ts);
+ if (res)
+ abort();
+ return ts.tv_sec;
+}
+
+/**
+ * FUSE connection expiration thread
+ *
+ */
+static void* hdfsConnExpiryThread(void *v)
+{
+ time_t nextTime, curTime;
+ int waitTime;
+
+ nextTime = getMonotonicTime() + gTimerPeriod;
+ while (1) {
+ curTime = getMonotonicTime();
+ if (curTime >= nextTime) {
+ hdfsConnExpiry();
+ nextTime = curTime + gTimerPeriod;
+ }
+ waitTime = (nextTime - curTime) * 1000;
+ poll(NULL, 0, waitTime);
+ }
+ return NULL;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_connect.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_connect.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_connect.h
new file mode 100644
index 0000000..35645c6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_connect.h
@@ -0,0 +1,90 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_CONNECT_H__
+#define __FUSE_CONNECT_H__
+
+struct fuse_context;
+struct hdfsConn;
+struct hdfs_internal;
+
+/**
+ * Initialize the fuse connection subsystem.
+ *
+ * This must be called before any of the other functions in this module.
+ *
+ * @param nnUri The NameNode URI
+ * @param port The NameNode port
+ *
+ * @return 0 on success; error code otherwise
+ */
+int fuseConnectInit(const char *nnUri, int port);
+
+/**
+ * Get a libhdfs connection.
+ *
+ * If there is an existing connection, it will be reused. If not, a new one
+ * will be created.
+ *
+ * You must call hdfsConnRelease on the connection you get back!
+ *
+ * @param usrname The username to use
+ * @param ctx The FUSE context to use (contains UID, PID of requestor)
+ * @param conn (out param) The HDFS connection
+ *
+ * @return 0 on success; error code otherwise
+ */
+int fuseConnect(const char *usrname, struct fuse_context *ctx,
+ struct hdfsConn **out);
+
+/**
+ * Get a libhdfs connection.
+ *
+ * The same as fuseConnect, except the username will be determined from the FUSE
+ * thread context.
+ *
+ * @param conn (out param) The HDFS connection
+ *
+ * @return 0 on success; error code otherwise
+ */
+int fuseConnectAsThreadUid(struct hdfsConn **conn);
+
+/**
+ * Test whether we can connect to the HDFS cluster
+ *
+ * @return 0 on success; error code otherwise
+ */
+int fuseConnectTest(void);
+
+/**
+ * Get the hdfsFS associated with an hdfsConn.
+ *
+ * @param conn The hdfsConn
+ *
+ * @return the hdfsFS
+ */
+struct hdfs_internal* hdfsConnGetFs(struct hdfsConn *conn);
+
+/**
+ * Release an hdfsConn when we're done with it.
+ *
+ * @param conn The hdfsConn
+ */
+void hdfsConnRelease(struct hdfsConn *conn);
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_context_handle.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_context_handle.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_context_handle.h
new file mode 100644
index 0000000..6929062
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_context_handle.h
@@ -0,0 +1,40 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_CONTEXT_HANDLE_H__
+#define __FUSE_CONTEXT_HANDLE_H__
+
+#include <hdfs.h>
+#include <stddef.h>
+#include <sys/types.h>
+
+//
+// Structure to store fuse_dfs specific data
+// this will be created and passed to fuse at startup
+// and fuse will pass it back to us via the context function
+// on every operation.
+//
+typedef struct dfs_context_struct {
+ int debug;
+ int usetrash;
+ int direct_io;
+ char **protectedpaths;
+ size_t rdbuffer_size;
+} dfs_context;
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs.c
new file mode 100644
index 0000000..f693032
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs.c
@@ -0,0 +1,136 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_options.h"
+#include "fuse_impls.h"
+#include "fuse_init.h"
+#include "fuse_connect.h"
+
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+int is_protected(const char *path) {
+
+ dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
+ assert(dfs != NULL);
+ assert(dfs->protectedpaths);
+
+ int i ;
+ for (i = 0; dfs->protectedpaths[i]; i++) {
+ if (strcmp(path, dfs->protectedpaths[i]) == 0) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static struct fuse_operations dfs_oper = {
+ .getattr = dfs_getattr,
+ .access = dfs_access,
+ .readdir = dfs_readdir,
+ .destroy = dfs_destroy,
+ .init = dfs_init,
+ .open = dfs_open,
+ .read = dfs_read,
+ .symlink = dfs_symlink,
+ .statfs = dfs_statfs,
+ .mkdir = dfs_mkdir,
+ .rmdir = dfs_rmdir,
+ .rename = dfs_rename,
+ .unlink = dfs_unlink,
+ .release = dfs_release,
+ .create = dfs_create,
+ .write = dfs_write,
+ .flush = dfs_flush,
+ .mknod = dfs_mknod,
+ .utimens = dfs_utimens,
+ .chmod = dfs_chmod,
+ .chown = dfs_chown,
+ .truncate = dfs_truncate,
+};
+
+int main(int argc, char *argv[])
+{
+ int ret;
+
+ umask(0);
+
+ extern const char *program;
+ program = argv[0];
+ struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
+
+ memset(&options, 0, sizeof(struct options));
+
+ options.rdbuffer_size = 10*1024*1024;
+ options.attribute_timeout = 60;
+ options.entry_timeout = 60;
+
+ if (-1 == fuse_opt_parse(&args, &options, dfs_opts, dfs_options)) {
+ return -1;
+ }
+
+ if (!options.private) {
+ fuse_opt_add_arg(&args, "-oallow_other");
+ }
+
+ if (!options.no_permissions) {
+ fuse_opt_add_arg(&args, "-odefault_permissions");
+ }
+ /*
+ * FUSE already has a built-in parameter for mounting the filesystem as
+ * read-only, -r. We defined our own parameter for doing this called -oro.
+ * We support it by translating it into -r internally.
+ * The kernel intercepts and returns an error message for any "write"
+ * operations that the user attempts to perform on a read-only filesystem.
+ * That means that we don't have to write any code to handle read-only mode.
+ * See HDFS-4139 for more details.
+ */
+ if (options.read_only) {
+ fuse_opt_add_arg(&args, "-r");
+ }
+
+ {
+ char buf[80];
+
+ snprintf(buf, sizeof buf, "-oattr_timeout=%d",options.attribute_timeout);
+ fuse_opt_add_arg(&args, buf);
+
+ snprintf(buf, sizeof buf, "-oentry_timeout=%d",options.entry_timeout);
+ fuse_opt_add_arg(&args, buf);
+ }
+
+ if (options.nn_uri == NULL) {
+ print_usage(argv[0]);
+ exit(EXIT_SUCCESS);
+ }
+
+ /* Note: do not call any libhdfs functions until fuse_main has been invoked.
+ *
+ * fuse_main will daemonize this process, by calling fork(). This will cause
+ * any extant threads to be destroyed, which could cause problems if
+ * libhdfs has started some Java threads.
+ *
+ * Most initialization code should go in dfs_init, which is invoked after the
+ * fork. See HDFS-3808 for details.
+ */
+ ret = fuse_main(args.argc, args.argv, &dfs_oper, NULL);
+ fuse_opt_free_args(&args);
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs.h
new file mode 100644
index 0000000..4554dbd
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs.h
@@ -0,0 +1,81 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_DFS_H__
+#define __FUSE_DFS_H__
+
+#define FUSE_USE_VERSION 26
+
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+#include <strings.h>
+#include <syslog.h>
+
+#include <fuse.h>
+#include <fuse/fuse_opt.h>
+
+#include <sys/xattr.h>
+
+#include "config.h"
+
+//
+// Check if a path is in the mount option supplied protected paths.
+//
+int is_protected(const char *path);
+
+#undef INFO
+#define INFO(_fmt, ...) { \
+ fprintf(stdout, "INFO %s:%d " _fmt "\n", \
+ __FILE__, __LINE__, ## __VA_ARGS__); \
+ syslog(LOG_INFO, "INFO %s:%d " _fmt "\n", \
+ __FILE__, __LINE__, ## __VA_ARGS__); \
+}
+
+#undef DEBUG
+#define DEBUG(_fmt, ...) { \
+ fprintf(stdout, "DEBUG %s:%d " _fmt "\n", \
+ __FILE__, __LINE__, ## __VA_ARGS__); \
+ syslog(LOG_DEBUG, "DEBUG %s:%d " _fmt "\n", \
+ __FILE__, __LINE__, ## __VA_ARGS__); \
+}
+
+#undef ERROR
+#define ERROR(_fmt, ...) { \
+ fprintf(stderr, "ERROR %s:%d " _fmt "\n", \
+ __FILE__, __LINE__, ## __VA_ARGS__); \
+ syslog(LOG_ERR, "ERROR %s:%d " _fmt "\n", \
+ __FILE__, __LINE__, ## __VA_ARGS__); \
+}
+
+//#define DOTRACE
+#ifdef DOTRACE
+#define TRACE(x) { \
+ DEBUG("TRACE %s", x); \
+}
+
+#define TRACE1(x,y) { \
+ DEBUG("TRACE %s %s\n", x, y); \
+}
+#else
+#define TRACE(x) ;
+#define TRACE1(x,y) ;
+#endif
+
+#endif // __FUSE_DFS_H__
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs_wrapper.sh
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs_wrapper.sh b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs_wrapper.sh
new file mode 100755
index 0000000..97239cc
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_dfs_wrapper.sh
@@ -0,0 +1,46 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+export HADOOP_PREFIX=${HADOOP_PREFIX:-/usr/local/share/hadoop}
+
+if [ "$OS_ARCH" = "" ]; then
+export OS_ARCH=amd64
+fi
+
+if [ "$JAVA_HOME" = "" ]; then
+export JAVA_HOME=/usr/local/java
+fi
+
+if [ "$LD_LIBRARY_PATH" = "" ]; then
+export LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/$OS_ARCH/server:/usr/local/lib
+fi
+
+# If dev build set paths accordingly
+if [ -d $HADOOP_PREFIX/build ]; then
+ export HADOOP_PREFIX=$HADOOP_PREFIX
+ for f in ${HADOOP_PREFIX}/build/*.jar ; do
+ export CLASSPATH=$CLASSPATH:$f
+ done
+ for f in $HADOOP_PREFIX/build/ivy/lib/hadoop-hdfs/common/*.jar ; do
+ export CLASSPATH=$CLASSPATH:$f
+ done
+ export PATH=$HADOOP_PREFIX/build/contrib/fuse-dfs:$PATH
+ export LD_LIBRARY_PATH=$HADOOP_PREFIX/build/c++/lib:$JAVA_HOME/jre/lib/$OS_ARCH/server
+fi
+
+fuse_dfs $@
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_file_handle.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_file_handle.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_file_handle.h
new file mode 100644
index 0000000..7f9346c
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_file_handle.h
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __FUSE_FILE_HANDLE_H__
+#define __FUSE_FILE_HANDLE_H__
+
+#include <hdfs.h>
+#include <pthread.h>
+
+struct hdfsConn;
+
+/**
+ *
+ * dfs_fh_struct is passed around for open files. Fuse provides a hook (the context)
+ * for storing file specific data.
+ *
+ * 2 Types of information:
+ * a) a read buffer for performance reasons since fuse is typically called on 4K chunks only
+ * b) the hdfs fs handle
+ *
+ */
+typedef struct dfs_fh_struct {
+ hdfsFile hdfsFH;
+ struct hdfsConn *conn;
+ char *buf;
+ tSize bufferSize; //what is the size of the buffer we have
+ off_t buffersStartOffset; //where the buffer starts in the file
+ pthread_mutex_t mutex;
+} dfs_fh;
+
+#endif
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls.h
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls.h b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls.h
new file mode 100644
index 0000000..d0d93e2
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls.h
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+
+#ifndef __FUSE_IMPLS_H__
+#define __FUSE_IMPLS_H__
+
+#include <fuse.h>
+#include <syslog.h>
+
+#include "fuse_context_handle.h"
+
+/**
+ * Implementations of the various fuse hooks.
+ * All of these (should be) thread safe.
+ *
+ */
+
+int dfs_mkdir(const char *path, mode_t mode);
+int dfs_rename(const char *from, const char *to);
+int dfs_getattr(const char *path, struct stat *st);
+int dfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
+ off_t offset, struct fuse_file_info *fi);
+int dfs_read(const char *path, char *buf, size_t size, off_t offset,
+ struct fuse_file_info *fi);
+int dfs_statfs(const char *path, struct statvfs *st);
+int dfs_mkdir(const char *path, mode_t mode);
+int dfs_rename(const char *from, const char *to);
+int dfs_rmdir(const char *path);
+int dfs_unlink(const char *path);
+int dfs_utimens(const char *path, const struct timespec ts[2]);
+int dfs_chmod(const char *path, mode_t mode);
+int dfs_chown(const char *path, uid_t uid, gid_t gid);
+int dfs_open(const char *path, struct fuse_file_info *fi);
+int dfs_write(const char *path, const char *buf, size_t size,
+ off_t offset, struct fuse_file_info *fi);
+int dfs_release (const char *path, struct fuse_file_info *fi);
+int dfs_mknod(const char *path, mode_t mode, dev_t rdev) ;
+int dfs_create(const char *path, mode_t mode, struct fuse_file_info *fi);
+int dfs_flush(const char *path, struct fuse_file_info *fi);
+int dfs_access(const char *path, int mask);
+int dfs_truncate(const char *path, off_t size);
+int dfs_symlink(const char *from, const char *to);
+
+#endif
+
+
+
http://git-wip-us.apache.org/repos/asf/hadoop/blob/3112f263/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_access.c
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_access.c b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_access.c
new file mode 100644
index 0000000..033a1c3
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/fuse-dfs/fuse_impls_access.c
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+#include "fuse_dfs.h"
+#include "fuse_impls.h"
+#include "fuse_connect.h"
+
+int dfs_access(const char *path, int mask)
+{
+ TRACE1("access", path)
+ assert(path != NULL);
+ // TODO: HDFS-428
+ return 0;
+}