You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@storm.apache.org by bo...@apache.org on 2014/05/21 18:07:08 UTC
[13/14] STORM-216: Added Authentication and Authorization.
http://git-wip-us.apache.org/repos/asf/incubator-storm/blob/fe5f41aa/storm-core/src/clj/backtype/storm/daemon/executor.clj
----------------------------------------------------------------------
diff --git a/storm-core/src/clj/backtype/storm/daemon/executor.clj b/storm-core/src/clj/backtype/storm/daemon/executor.clj
index f133a1b..d193a9f 100644
--- a/storm-core/src/clj/backtype/storm/daemon/executor.clj
+++ b/storm-core/src/clj/backtype/storm/daemon/executor.clj
@@ -16,13 +16,15 @@
(ns backtype.storm.daemon.executor
(:use [backtype.storm.daemon common])
(:use [backtype.storm bootstrap])
+ (:import [backtype.storm ICredentialsListener])
(:import [backtype.storm.hooks ITaskHook])
(:import [backtype.storm.tuple Tuple])
(:import [backtype.storm.spout ISpoutWaitStrategy])
(:import [backtype.storm.hooks.info SpoutAckInfo SpoutFailInfo
EmitInfo BoltFailInfo BoltAckInfo BoltExecuteInfo])
- (:import [backtype.storm.metric.api IMetric IMetricsConsumer$TaskInfo IMetricsConsumer$DataPoint StateMetric])
+ (:import [backtype.storm.metric.api IMetric IMetricsConsumer$TaskInfo IMetricsConsumer$DataPoint])
(:import [backtype.storm Config])
+ (:import [java.util.concurrent ConcurrentLinkedQueue])
(:require [backtype.storm [tuple :as tuple]])
(:require [backtype.storm.daemon [task :as task]])
(:require [backtype.storm.daemon.builtin-metrics :as builtin-metrics]))
@@ -157,7 +159,8 @@
(defprotocol RunningExecutor
(render-stats [this])
- (get-executor-id [this]))
+ (get-executor-id [this])
+ (credentials-changed [this creds]))
(defn throttled-report-error-fn [executor]
(let [storm-conf (:storm-conf executor)
@@ -179,9 +182,11 @@
))))
;; in its own function so that it can be mocked out by tracked topologies
-(defn mk-executor-transfer-fn [batch-transfer->worker]
+(defn mk-executor-transfer-fn [batch-transfer->worker storm-conf]
(fn this
- ([task tuple block? ^List overflow-buffer]
+ ([task tuple block? ^ConcurrentLinkedQueue overflow-buffer]
+ (when (= true (storm-conf TOPOLOGY-DEBUG))
+ (log-message "TRANSFERING tuple TASK: " task " TUPLE: " tuple))
(if (and overflow-buffer (not (.isEmpty overflow-buffer)))
(.add overflow-buffer [task tuple])
(try-cause
@@ -222,7 +227,7 @@
:shared-executor-data (HashMap.)
:storm-active-atom (:storm-active-atom worker)
:batch-transfer-queue batch-transfer->worker
- :transfer-fn (mk-executor-transfer-fn batch-transfer->worker)
+ :transfer-fn (mk-executor-transfer-fn batch-transfer->worker storm-conf)
:suicide-fn (:suicide-fn worker)
:storm-cluster-state (cluster/mk-storm-cluster-state (:cluster-state worker))
:type executor-type
@@ -312,7 +317,7 @@
[[nil (TupleImpl. context [tick-time-secs] Constants/SYSTEM_TASK_ID Constants/SYSTEM_TICK_STREAM_ID)]]
)))))))
-(defn mk-executor [worker executor-id]
+(defn mk-executor [worker executor-id initial-credentials]
(let [executor-data (mk-executor-data worker executor-id)
_ (log-message "Loading executor " (:component-id executor-data) ":" (pr-str executor-id))
task-datas (->> executor-data
@@ -329,7 +334,7 @@
;; trick isn't thread-safe)
system-threads [(start-batch-transfer->worker-handler! worker executor-data)]
handlers (with-error-reaction report-error-and-die
- (mk-threads executor-data task-datas))
+ (mk-threads executor-data task-datas initial-credentials))
threads (concat handlers system-threads)]
(setup-ticks! worker executor-data)
@@ -341,6 +346,13 @@
(stats/render-stats! (:stats executor-data)))
(get-executor-id [this]
executor-id )
+ (credentials-changed [this creds]
+ (let [receive-queue (:receive-queue executor-data)
+ context (:worker-context executor-data)]
+ (disruptor/publish
+ receive-queue
+ [[nil (TupleImpl. context [creds] Constants/SYSTEM_TASK_ID Constants/CREDENTIALS_CHANGED_STREAM_ID)]]
+ )))
Shutdownable
(shutdown
[this]
@@ -361,23 +373,25 @@
(log-message "Shut down executor " component-id ":" (pr-str executor-id)))
)))
-(defn- fail-spout-msg [executor-data task-data msg-id tuple-info time-delta]
+(defn- fail-spout-msg [executor-data task-data msg-id tuple-info time-delta reason id]
(let [^ISpout spout (:object task-data)
+ storm-conf (:storm-conf executor-data)
task-id (:task-id task-data)]
;;TODO: need to throttle these when there's lots of failures
- (log-debug "Failing message " msg-id ": " tuple-info)
+ (when (= true (storm-conf TOPOLOGY-DEBUG))
+ (log-message "SPOUT Failing " id ": " tuple-info " REASON: " reason " MSG-ID: " msg-id))
(.fail spout msg-id)
(task/apply-hooks (:user-context task-data) .spoutFail (SpoutFailInfo. msg-id task-id time-delta))
(when time-delta
(builtin-metrics/spout-failed-tuple! (:builtin-metrics task-data) (:stats executor-data) (:stream tuple-info))
(stats/spout-failed-tuple! (:stats executor-data) (:stream tuple-info) time-delta))))
-(defn- ack-spout-msg [executor-data task-data msg-id tuple-info time-delta]
+(defn- ack-spout-msg [executor-data task-data msg-id tuple-info time-delta id]
(let [storm-conf (:storm-conf executor-data)
^ISpout spout (:object task-data)
task-id (:task-id task-data)]
(when (= true (storm-conf TOPOLOGY-DEBUG))
- (log-message "Acking message " msg-id))
+ (log-message "SPOUT Acking message " id " " msg-id))
(.ack spout msg-id)
(task/apply-hooks (:user-context task-data) .spoutAck (SpoutAckInfo. msg-id task-id time-delta))
(when time-delta
@@ -393,7 +407,7 @@
(fn [tuple-batch sequence-id end-of-batch?]
(fast-list-iter [[task-id msg] tuple-batch]
(let [^TupleImpl tuple (if (instance? Tuple msg) msg (.deserialize deserializer msg))]
- (when debug? (log-message "Processing received message " tuple))
+ (when debug? (log-message "Processing received message FOR " task-id " TUPLE: " tuple))
(if task-id
(tuple-action-fn task-id tuple)
;; null task ids are broadcast tuples
@@ -412,7 +426,7 @@
ret
))
-(defmethod mk-threads :spout [executor-data task-datas]
+(defmethod mk-threads :spout [executor-data task-datas initial-credentials]
(let [{:keys [storm-conf component-id worker-context transfer-fn report-error sampler open-or-prepare-was-called?]} executor-data
^ISpoutWaitStrategy spout-wait-strategy (init-spout-wait-strategy storm-conf)
max-spout-pending (executor-max-spout-pending storm-conf (count task-datas))
@@ -424,15 +438,20 @@
pending (RotatingMap.
2 ;; microoptimize for performance of .size method
(reify RotatingMap$ExpiredCallback
- (expire [this msg-id [task-id spout-id tuple-info start-time-ms]]
+ (expire [this id [task-id spout-id tuple-info start-time-ms]]
(let [time-delta (if start-time-ms (time-delta-ms start-time-ms))]
- (fail-spout-msg executor-data (get task-datas task-id) spout-id tuple-info time-delta)
+ (fail-spout-msg executor-data (get task-datas task-id) spout-id tuple-info time-delta "TIMEOUT" id)
))))
tuple-action-fn (fn [task-id ^TupleImpl tuple]
(let [stream-id (.getSourceStreamId tuple)]
(condp = stream-id
Constants/SYSTEM_TICK_STREAM_ID (.rotate pending)
Constants/METRICS_TICK_STREAM_ID (metrics-tick executor-data task-datas tuple)
+ Constants/CREDENTIALS_CHANGED_STREAM_ID
+ (let [task-data (get task-datas task-id)
+ spout-obj (:object task-data)]
+ (when (instance? ICredentialsListener spout-obj)
+ (.setCredentials spout-obj (.getValue tuple 0))))
(let [id (.getValue tuple 0)
[stored-task-id spout-id tuple-finished-info start-time-ms] (.remove pending id)]
(when spout-id
@@ -441,9 +460,9 @@
(let [time-delta (if start-time-ms (time-delta-ms start-time-ms))]
(condp = stream-id
ACKER-ACK-STREAM-ID (ack-spout-msg executor-data (get task-datas task-id)
- spout-id tuple-finished-info time-delta)
+ spout-id tuple-finished-info time-delta id)
ACKER-FAIL-STREAM-ID (fail-spout-msg executor-data (get task-datas task-id)
- spout-id tuple-finished-info time-delta)
+ spout-id tuple-finished-info time-delta "FAIL-STREAM" id)
)))
;; TODO: on failure, emit tuple to failure stream
))))
@@ -460,7 +479,7 @@
;; when the overflow buffer is full, spouts stop calling nextTuple until it's able to clear the overflow buffer
;; this limits the size of the overflow buffer to however many tuples a spout emits in one call of nextTuple,
;; preventing memory issues
- overflow-buffer (LinkedList.)]
+ overflow-buffer (ConcurrentLinkedQueue.)]
[(async-loop
(fn []
@@ -471,8 +490,8 @@
(log-message "Opening spout " component-id ":" (keys task-datas))
(doseq [[task-id task-data] task-datas
:let [^ISpout spout-obj (:object task-data)
- tasks-fn (:tasks-fn task-data)
- send-spout-msg (fn [out-stream-id values message-id out-task-id]
+ tasks-fn (:tasks-fn task-data)
+ send-spout-msg (fn [out-stream-id values message-id out-task-id]
(.increment emitted-count)
(let [out-tasks (if out-task-id
(tasks-fn out-task-id out-stream-id values)
@@ -506,13 +525,14 @@
(when message-id
(ack-spout-msg executor-data task-data message-id
{:stream out-stream-id :values values}
- (if (sampler) 0))))
+ (if (sampler) 0) "0:")))
(or out-tasks [])
))]]
(builtin-metrics/register-all (:builtin-metrics task-data) storm-conf (:user-context task-data))
(builtin-metrics/register-queue-metrics {:sendqueue (:batch-transfer-queue executor-data)
:receive receive-queue}
storm-conf (:user-context task-data))
+ (when (instance? ICredentialsListener spout-obj) (.setCredentials spout-obj initial-credentials))
(.open spout-obj
storm-conf
@@ -543,7 +563,7 @@
(while (not (.isEmpty overflow-buffer))
(let [[out-task out-tuple] (.peek overflow-buffer)]
(transfer-fn out-task out-tuple false nil)
- (.removeFirst overflow-buffer)))
+ (.poll overflow-buffer)))
(catch InsufficientCapacityException e
))
@@ -591,8 +611,9 @@
(let [curr (or (.get pending key) (long 0))]
(.put pending key (bit-xor curr id))))
-(defmethod mk-threads :bolt [executor-data task-datas]
- (let [execute-sampler (mk-stats-sampler (:storm-conf executor-data))
+(defmethod mk-threads :bolt [executor-data task-datas initial-credentials]
+ (let [storm-conf (:storm-conf executor-data)
+ execute-sampler (mk-stats-sampler storm-conf)
executor-stats (:stats executor-data)
{:keys [storm-conf component-id worker-context transfer-fn report-error sampler
open-or-prepare-was-called?]} executor-data
@@ -616,6 +637,11 @@
;; need to do it this way to avoid reflection
(let [stream-id (.getSourceStreamId tuple)]
(condp = stream-id
+ Constants/CREDENTIALS_CHANGED_STREAM_ID
+ (let [task-data (get task-datas task-id)
+ bolt-obj (:object task-data)]
+ (when (instance? ICredentialsListener bolt-obj)
+ (.setCredentials bolt-obj (.getValue tuple 0))))
Constants/METRICS_TICK_STREAM_ID (metrics-tick executor-data task-datas tuple)
(let [task-data (get task-datas task-id)
^IBolt bolt-obj (:object task-data)
@@ -629,6 +655,9 @@
(.setExecuteSampleStartTime tuple now))
(.execute bolt-obj tuple)
(let [delta (tuple-execute-time-delta! tuple)]
+ (when (= true (storm-conf TOPOLOGY-DEBUG))
+ (log-message "Execute done TUPLE " tuple " TASK: " task-id " DELTA: " delta))
+
(task/apply-hooks user-context .boltExecute (BoltExecuteInfo. tuple task-id delta))
(when delta
(builtin-metrics/bolt-execute-tuple! (:builtin-metrics task-data)
@@ -639,7 +668,16 @@
(stats/bolt-execute-tuple! executor-stats
(.getSourceComponent tuple)
(.getSourceStreamId tuple)
- delta)))))))]
+ delta)))))))
+
+ ;; the overflow buffer is used to ensure that bolts do not block when emitting
+ ;; this ensures that the bolt can always clear the incoming messages, which
+ ;; prevents deadlock from occurs across the topology
+ ;; (e.g. Spout -> BoltA -> Splitter -> BoltB -> BoltA, and all
+ ;; buffers filled up)
+ ;; the overflow buffer is might gradually fill degrading the performance gradually
+ ;; eventually running out of memory, but at least prevent live-locks/deadlocks.
+ overflow-buffer (ConcurrentLinkedQueue.)]
;; TODO: can get any SubscribedState objects out of the context now
@@ -673,9 +711,11 @@
values
task-id
stream
- (MessageId/makeId anchors-to-ids)))))
+ (MessageId/makeId anchors-to-ids))
+ overflow-buffer)))
(or out-tasks [])))]]
(builtin-metrics/register-all (:builtin-metrics task-data) storm-conf user-context)
+ (when (instance? ICredentialsListener bolt-obj) (.setCredentials bolt-obj initial-credentials))
(if (= component-id Constants/SYSTEM_COMPONENT_ID)
(builtin-metrics/register-queue-metrics {:sendqueue (:batch-transfer-queue executor-data)
:receive (:receive-queue executor-data)
@@ -701,9 +741,12 @@
(fast-map-iter [[root id] (.. tuple getMessageId getAnchorsToIds)]
(task/send-unanchored task-data
ACKER-ACK-STREAM-ID
- [root (bit-xor id ack-val)])
+ [root (bit-xor id ack-val)] overflow-buffer)
))
- (let [delta (tuple-time-delta! tuple)]
+ (let [delta (tuple-time-delta! tuple)
+ debug? (= true (storm-conf TOPOLOGY-DEBUG))]
+ (when debug?
+ (log-message "BOLT ack TASK: " task-id " TIME: " delta " TUPLE: " tuple))
(task/apply-hooks user-context .boltAck (BoltAckInfo. tuple task-id delta))
(when delta
(builtin-metrics/bolt-acked-tuple! (:builtin-metrics task-data)
@@ -719,8 +762,11 @@
(fast-list-iter [root (.. tuple getMessageId getAnchors)]
(task/send-unanchored task-data
ACKER-FAIL-STREAM-ID
- [root]))
- (let [delta (tuple-time-delta! tuple)]
+ [root] overflow-buffer))
+ (let [delta (tuple-time-delta! tuple)
+ debug? (= true (storm-conf TOPOLOGY-DEBUG))]
+ (when debug?
+ (log-message "BOLT fail TASK: " task-id " TIME: " delta " TUPLE: " tuple))
(task/apply-hooks user-context .boltFail (BoltFailInfo. tuple task-id delta))
(when delta
(builtin-metrics/bolt-failed-tuple! (:builtin-metrics task-data)
@@ -743,6 +789,16 @@
(disruptor/consumer-started! receive-queue)
(fn []
(disruptor/consume-batch-when-available receive-queue event-handler)
+ ;; try to clear the overflow-buffer
+ (try-cause
+ (while (not (.isEmpty overflow-buffer))
+ (let [[out-task out-tuple] (.peek overflow-buffer)]
+ (transfer-fn out-task out-tuple false nil)
+ (.poll overflow-buffer)))
+ (catch InsufficientCapacityException e
+ (when (= true (storm-conf TOPOLOGY-DEBUG))
+ (log-message "Insufficient Capacity on queue to emit by bolt " component-id ":" (keys task-datas) ))
+ ))
0)))
:kill-fn (:report-error-and-die executor-data)
:factory? true
http://git-wip-us.apache.org/repos/asf/incubator-storm/blob/fe5f41aa/storm-core/src/clj/backtype/storm/daemon/logviewer.clj
----------------------------------------------------------------------
diff --git a/storm-core/src/clj/backtype/storm/daemon/logviewer.clj b/storm-core/src/clj/backtype/storm/daemon/logviewer.clj
index 2a48f55..36a737f 100644
--- a/storm-core/src/clj/backtype/storm/daemon/logviewer.clj
+++ b/storm-core/src/clj/backtype/storm/daemon/logviewer.clj
@@ -15,38 +15,180 @@
;; limitations under the License.
(ns backtype.storm.daemon.logviewer
(:use compojure.core)
+ (:use [clojure.set :only [difference]])
+ (:use [clojure.string :only [blank?]])
(:use [hiccup core page-helpers])
- (:use [backtype.storm config util log])
+ (:use [backtype.storm config util log timer])
+ (:use [backtype.storm.ui helpers])
(:use [ring.adapter.jetty :only [run-jetty]])
(:import [org.slf4j LoggerFactory])
(:import [ch.qos.logback.classic Logger])
- (:import [org.apache.commons.logging LogFactory])
- (:import [org.apache.commons.logging.impl Log4JLogger])
(:import [ch.qos.logback.core FileAppender])
- (:import [org.apache.log4j Level])
- (:import [java.io File])
+ (:import [java.io File FileFilter FileInputStream])
+ (:import [org.yaml.snakeyaml Yaml]
+ [org.yaml.snakeyaml.constructor SafeConstructor])
+ (:import [backtype.storm.ui InvalidRequestException]
+ [backtype.storm.security.auth AuthUtils])
(:require [compojure.route :as route]
[compojure.handler :as handler]
+ [ring.middleware.keyword-params]
+ [ring.util.response :as resp])
+ (:require [backtype.storm.daemon common [supervisor :as supervisor]])
+ (:import [java.io File FileFilter])
+ (:require [compojure.route :as route]
+ [compojure.handler :as handler]
+ [ring.util.response :as resp]
[clojure.string :as string])
(:gen-class))
-(defn tail-file [path tail root-dir]
- (let [flen (.length (clojure.java.io/file path))
- skip (- flen tail)
- log-dir (.getCanonicalFile (File. root-dir))
- log-file (File. path)]
- (if (= log-dir (.getParentFile log-file))
- (with-open [input (clojure.java.io/input-stream path)
- output (java.io.ByteArrayOutputStream.)]
- (if (> skip 0) (.skip input skip))
- (let [buffer (make-array Byte/TYPE 1024)]
- (loop []
- (let [size (.read input buffer)]
- (when (and (pos? size) (< (.size output) tail))
- (do (.write output buffer 0 size)
- (recur))))))
- (.toString output)) "File not found")
- ))
+(def ^:dynamic *STORM-CONF* (read-storm-config))
+
+(defn cleanup-cutoff-age-millis [conf now-millis]
+ (- now-millis (* (conf LOGVIEWER-CLEANUP-AGE-MINS) 60 1000)))
+
+(defn mk-FileFilter-for-log-cleanup [conf now-millis]
+ (let [cutoff-age-millis (cleanup-cutoff-age-millis conf now-millis)]
+ (reify FileFilter (^boolean accept [this ^File file]
+ (boolean (and
+ (.isFile file)
+ (re-find worker-log-filename-pattern (.getName file))
+ (<= (.lastModified file) cutoff-age-millis)))))))
+
+(defn select-files-for-cleanup [conf now-millis root-dir]
+ (let [file-filter (mk-FileFilter-for-log-cleanup conf now-millis)]
+ (.listFiles (File. root-dir) file-filter)))
+
+(defn get-metadata-file-for-log-root-name [root-name root-dir]
+ (let [metaFile (clojure.java.io/file root-dir "metadata"
+ (str root-name ".yaml"))]
+ (if (.exists metaFile)
+ metaFile
+ (do
+ (log-warn "Could not find " (.getCanonicalPath metaFile)
+ " to clean up for " root-name)
+ nil))))
+
+(defn get-worker-id-from-metadata-file [metaFile]
+ (get (clojure-from-yaml-file metaFile) "worker-id"))
+
+(defn get-topo-owner-from-metadata-file [metaFile]
+ (get (clojure-from-yaml-file metaFile) TOPOLOGY-SUBMITTER-USER))
+
+(defn get-log-root->files-map [log-files]
+ "Returns a map of \"root name\" to a the set of files in log-files having the
+ root name. The \"root name\" of a log file is the part of the name preceding
+ the extension."
+ (reduce #(assoc %1 ;; The accumulated map so far
+ (first %2) ;; key: The root name of the log file
+ (conj (%1 (first %2) #{}) (second %2))) ;; val: The set of log files with the root name
+ {} ;; initial (empty) map
+ (map #(list
+ (second (re-find worker-log-filename-pattern (.getName %))) ;; The root name of the log file
+ %) ;; The log file
+ log-files)))
+
+(defn identify-worker-log-files [log-files root-dir]
+ (into {} (for [log-root-entry (get-log-root->files-map log-files)
+ :let [metaFile (get-metadata-file-for-log-root-name
+ (key log-root-entry) root-dir)
+ log-root (key log-root-entry)
+ files (val log-root-entry)]
+ :when metaFile]
+ {(get-worker-id-from-metadata-file metaFile)
+ {:owner (get-topo-owner-from-metadata-file metaFile)
+ :files
+ ;; If each log for this root name is to be deleted, then
+ ;; include the metadata file also.
+ (if (empty? (difference
+ (set (filter #(re-find (re-pattern log-root) %)
+ (read-dir-contents root-dir)))
+ (set (map #(.getName %) files))))
+ (conj files metaFile)
+ ;; Otherwise, keep the list of files as it is.
+ files)}})))
+
+(defn get-dead-worker-files-and-owners [conf now-secs log-files root-dir]
+ (if (empty? log-files)
+ {}
+ (let [id->heartbeat (supervisor/read-worker-heartbeats conf)
+ alive-ids (keys (remove
+ #(or (not (val %))
+ (supervisor/is-worker-hb-timed-out? now-secs (val %) conf))
+ id->heartbeat))
+ id->entries (identify-worker-log-files log-files root-dir)]
+ (for [[id {:keys [owner files]}] id->entries
+ :when (not (contains? (set alive-ids) id))]
+ {:owner owner
+ :files files}))))
+
+(defn cleanup-fn! [log-root-dir]
+ (let [now-secs (current-time-secs)
+ old-log-files (select-files-for-cleanup *STORM-CONF* (* now-secs 1000) log-root-dir)
+ dead-worker-files (get-dead-worker-files-and-owners *STORM-CONF* now-secs old-log-files log-root-dir)]
+ (log-debug "log cleanup: now(" now-secs
+ ") old log files (" (seq (map #(.getName %) old-log-files))
+ ") dead worker files (" (seq (map #(.getName %) dead-worker-files)) ")")
+ (dofor [{:keys [owner files]} dead-worker-files
+ file files]
+ (let [path (.getCanonicalPath file)]
+ (log-message "Cleaning up: Removing " path)
+ (try
+ (if (or (blank? owner) (re-matches #".*\.yaml$" path))
+ (rmr path)
+ ;; worker-launcher does not actually launch a worker process. It
+ ;; merely executes one of a prescribed set of commands. In this case, we ask it
+ ;; to delete a file as the owner of that file.
+ (supervisor/worker-launcher *STORM-CONF* owner (str "rmr " path)))
+ (catch Exception ex
+ (log-error ex)))))))
+
+(defn start-log-cleaner! [conf log-root-dir]
+ (let [interval-secs (conf LOGVIEWER-CLEANUP-INTERVAL-SECS)]
+ (when interval-secs
+ (log-debug "starting log cleanup thread at interval: " interval-secs)
+ (schedule-recurring (mk-timer :thread-name "logviewer-cleanup")
+ 0 ;; Start immediately.
+ interval-secs
+ (fn [] (cleanup-fn! log-root-dir))))))
+
+(defn page-file
+ ([path tail]
+ (let [flen (.length (clojure.java.io/file path))
+ skip (- flen tail)]
+ (page-file path skip tail)))
+ ([path start length]
+ (with-open [input (FileInputStream. path)
+ output (java.io.ByteArrayOutputStream.)]
+ (if (>= start (.length (clojure.java.io/file path)))
+ (throw
+ (InvalidRequestException. "Cannot start past the end of the file")))
+ (if (> start 0)
+ ;; FileInputStream#skip may not work the first time.
+ (loop [skipped 0]
+ (let [skipped (+ skipped (.skip input (- start skipped)))]
+ (if (< skipped start) (recur skipped)))))
+ (let [buffer (make-array Byte/TYPE 1024)]
+ (loop []
+ (when (< (.size output) length)
+ (let [size (.read input buffer 0 (min 1024 (- length (.size output))))]
+ (when (pos? size)
+ (.write output buffer 0 size)
+ (recur)))))
+ (.toString output)))))
+
+(defn get-log-user-whitelist [fname]
+ (let [wl-file (get-log-metadata-file fname)
+ m (clojure-from-yaml-file wl-file)]
+ (if-let [whitelist (.get m LOGS-USERS)] whitelist [])))
+
+(defn authorized-log-user? [user fname conf]
+ (if (or (blank? user) (blank? fname))
+ nil
+ (let [whitelist (get-log-user-whitelist fname)
+ logs-users (concat (conf LOGS-USERS)
+ (conf NIMBUS-ADMINS)
+ whitelist)]
+ (some #(= % user) logs-users))))
(defn log-root-dir
"Given an appender name, as configured, get the parent directory of the appender's log file.
@@ -59,61 +201,168 @@ Note that if anything goes wrong, this will throw an Error and exit."
(throw
(RuntimeException. "Log viewer could not find configured appender, or the appender is not a FileAppender. Please check that the appender name configured in storm and logback agree.")))))
-(defn log-page [file tail grep root-dir]
- (let [path (.getCanonicalPath (File. root-dir file))
- tail (if tail
- (min 10485760 (Integer/parseInt tail))
- 10240)
- tail-string (tail-file path tail root-dir)]
- (if grep
- (clojure.string/join "\n<br>"
- (filter #(.contains % grep) (.split tail-string "\n")))
- (.replaceAll tail-string "\n" "\n<br>"))))
-
-(defn log-level-page [name level]
- (let [log (LogFactory/getLog name)]
- (if level
- (if (instance? Log4JLogger log)
- (.setLevel (.getLogger log) (Level/toLevel level))))
- (str "effective log level for " name " is " (.getLevel (.getLogger log)))))
-
-(defn log-template [body]
- (html4
- [:head
- [:title "Storm log viewer"]
- (include-css "/css/bootstrap-1.4.0.css")
- (include-css "/css/style.css")
- (include-js "/js/jquery-1.6.2.min.js")
- (include-js "/js/jquery.tablesorter.min.js")
- (include-js "/js/jquery.cookies.2.2.0.min.js")
- (include-js "/js/script.js")
- ]
- [:body
- (seq body)
- ]))
+(defn pager-links [fname start length file-size]
+ (let [prev-start (max 0 (- start length))
+ next-start (if (> file-size 0)
+ (min (max 0 (- file-size length)) (+ start length))
+ (+ start length))]
+ [[:div.pagination
+ [:ul
+ (concat
+ [[(if (< prev-start start) (keyword "li") (keyword "li.disabled"))
+ (link-to (url "/log"
+ {:file fname
+ :start (max 0 (- start length))
+ :length length})
+ "Prev")]]
+ [[:li (link-to
+ (url "/log"
+ {:file fname
+ :start 0
+ :length length})
+ "First")]]
+ [[:li (link-to
+ (url "/log"
+ {:file fname
+ :length length})
+ "Last")]]
+ [[(if (> next-start start) (keyword "li.next") (keyword "li.next.disabled"))
+ (link-to (url "/log"
+ {:file fname
+ :start (min (max 0 (- file-size length))
+ (+ start length))
+ :length length})
+ "Next")]])]]]))
+
+(defn- download-link [fname]
+ [[:p (link-to (url-format "/download/%s" fname) "Download Full Log")]])
+
+(defn log-page [fname start length grep user root-dir]
+ (if (or (blank? (*STORM-CONF* UI-FILTER))
+ (authorized-log-user? user fname *STORM-CONF*))
+ (let [file (.getCanonicalFile (File. root-dir fname))
+ file-length (.length file)
+ path (.getCanonicalPath file)]
+ (if (= (File. root-dir)
+ (.getParentFile file))
+ (let [default-length 51200
+ length (if length
+ (min 10485760 length)
+ default-length)
+ log-string (escape-html
+ (if start
+ (page-file path start length)
+ (page-file path length)))
+ start (or start (- file-length length))]
+ (if grep
+ (html [:pre#logContent
+ (if grep
+ (filter #(.contains % grep)
+ (.split log-string "\n"))
+ log-string)])
+ (let [pager-data (pager-links fname start length file-length)]
+ (html (concat pager-data
+ (download-link fname)
+ [[:pre#logContent log-string]]
+ pager-data)))))
+ (-> (resp/response "Page not found")
+ (resp/status 404))))
+ (unauthorized-user-html user)))
+
+(defn download-log-file [fname req resp user ^String root-dir]
+ (let [file (.getCanonicalFile (File. root-dir fname))]
+ (if (= (File. root-dir) (.getParentFile file))
+ (if (or (blank? (*STORM-CONF* UI-FILTER))
+ (authorized-log-user? user fname *STORM-CONF*))
+ (-> (resp/response file)
+ (resp/content-type "application/octet-stream"))
+ (unauthorized-user-html user))
+ (-> (resp/response "Page not found")
+ (resp/status 404)))))
+
+(defn log-template
+ ([body] (log-template body nil nil))
+ ([body fname user]
+ (html4
+ [:head
+ [:title (str (escape-html fname) " - Storm Log Viewer")]
+ (include-css "/css/bootstrap-1.4.0.css")
+ (include-css "/css/style.css")
+ ]
+ [:body
+ (concat
+ (when (not (blank? user)) [[:div.ui-user [:p "User: " user]]])
+ [[:h3 (escape-html fname)]]
+ (seq body))
+ ])))
+
+(def http-creds-handler (AuthUtils/GetUiHttpCredentialsPlugin *STORM-CONF*))
+
+(defn- parse-long-from-map [m k]
+ (try
+ (Long/parseLong (k m))
+ (catch NumberFormatException ex
+ (throw (InvalidRequestException.
+ (str "Could not make an integer out of the query parameter '"
+ (name k) "'")
+ ex)))))
(defroutes log-routes
(GET "/log" [:as req & m]
- (log-template (log-page (:file m) (:tail m) (:grep m) (:log-root req))))
- (GET "/loglevel" [:as {cookies :cookies} & m]
- (log-template (log-level-page (:name m) (:level m))))
+ (try
+ (let [servlet-request (:servlet-request req)
+ log-root (:log-root req)
+ user (.getUserName http-creds-handler servlet-request)
+ start (if (:start m) (parse-long-from-map m :start))
+ length (if (:length m) (parse-long-from-map m :length))]
+ (log-template (log-page (:file m) start length (:grep m) user log-root)
+ (:file m) user))
+ (catch InvalidRequestException ex
+ (log-error ex)
+ (ring-response-from-exception ex))))
+ (GET "/download/:file" [:as {:keys [servlet-request servlet-response log-root]} file & m]
+ (try
+ (let [user (.getUserName http-creds-handler servlet-request)]
+ (download-log-file file servlet-request servlet-response user log-root))
+ (catch InvalidRequestException ex
+ (log-error ex)
+ (ring-response-from-exception ex))))
(route/resources "/")
(route/not-found "Page not found"))
-(def logapp
- (handler/site log-routes)
- )
-
(defn conf-middleware
"For passing the storm configuration with each request."
[app log-root]
(fn [req]
(app (assoc req :log-root log-root))))
-(defn start-logviewer [port log-root]
- (run-jetty (conf-middleware logapp log-root) {:port port}))
+(defn start-logviewer! [conf log-root-dir]
+ (try
+ (let [header-buffer-size (int (.get conf UI-HEADER-BUFFER-BYTES))
+ filter-class (conf UI-FILTER)
+ filter-params (conf UI-FILTER-PARAMS)
+ logapp (handler/api log-routes) ;; query params as map
+ middle (conf-middleware logapp log-root-dir)
+ filters-confs (if (conf UI-FILTER)
+ [{:filter-class filter-class
+ :filter-params (or (conf UI-FILTER-PARAMS) {})}]
+ [])
+ filters-confs (concat filters-confs
+ [{:filter-class "org.mortbay.servlet.GzipFilter"
+ :filter-name "Gzipper"
+ :filter-params {}}])]
+ (run-jetty middle
+ {:port (int (conf LOGVIEWER-PORT))
+ :join? false
+ :configurator (fn [server]
+ (doseq [connector (.getConnectors server)]
+ (.setHeaderBufferSize connector header-buffer-size))
+ (config-filter server middle filters-confs))}))
+ (catch Exception ex
+ (log-error ex))))
(defn -main []
(let [conf (read-storm-config)
log-root (log-root-dir (conf LOGVIEWER-APPENDER-NAME))]
- (start-logviewer (int (conf LOGVIEWER-PORT)) log-root)))
+ (start-log-cleaner! conf log-root)
+ (start-logviewer! conf log-root)))
http://git-wip-us.apache.org/repos/asf/incubator-storm/blob/fe5f41aa/storm-core/src/clj/backtype/storm/daemon/nimbus.clj
----------------------------------------------------------------------
diff --git a/storm-core/src/clj/backtype/storm/daemon/nimbus.clj b/storm-core/src/clj/backtype/storm/daemon/nimbus.clj
index bf22a1b..0bd5337 100644
--- a/storm-core/src/clj/backtype/storm/daemon/nimbus.clj
+++ b/storm-core/src/clj/backtype/storm/daemon/nimbus.clj
@@ -14,19 +14,18 @@
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns backtype.storm.daemon.nimbus
- (:import [org.apache.thrift.server THsHaServer THsHaServer$Args])
- (:import [org.apache.thrift.protocol TBinaryProtocol TBinaryProtocol$Factory])
- (:import [org.apache.thrift.exception])
- (:import [org.apache.thrift.transport TNonblockingServerTransport TNonblockingServerSocket])
(:import [java.nio ByteBuffer])
(:import [java.io FileNotFoundException])
(:import [java.nio.channels Channels WritableByteChannel])
+ (:import [backtype.storm.security.auth ThriftServer ThriftConnectionType ReqContext AuthUtils])
(:use [backtype.storm.scheduler.DefaultScheduler])
(:import [backtype.storm.scheduler INimbus SupervisorDetails WorkerSlot TopologyDetails
Cluster Topologies SchedulerAssignment SchedulerAssignmentImpl DefaultScheduler ExecutorDetails])
+ (:import [backtype.storm.generated AuthorizationException])
(:use [backtype.storm bootstrap util])
(:use [backtype.storm.config :only [validate-configs-with-schemas]])
(:use [backtype.storm.daemon common])
+ (:import [org.apache.zookeeper data.ACL ZooDefs$Ids ZooDefs$Perms])
(:gen-class
:methods [^{:static true} [launch [backtype.storm.scheduler.INimbus] void]]))
@@ -59,13 +58,22 @@
scheduler
))
+(def NIMBUS-ZK-ACLS
+ [(first ZooDefs$Ids/CREATOR_ALL_ACL)
+ (ACL. (bit-or ZooDefs$Perms/READ ZooDefs$Perms/CREATE) ZooDefs$Ids/ANYONE_ID_UNSAFE)])
+
(defn nimbus-data [conf inimbus]
(let [forced-scheduler (.getForcedScheduler inimbus)]
{:conf conf
:inimbus inimbus
+ :authorization-handler (mk-authorization-handler (conf NIMBUS-AUTHORIZER) conf)
:submitted-count (atom 0)
- :storm-cluster-state (cluster/mk-storm-cluster-state conf)
+ :storm-cluster-state (cluster/mk-storm-cluster-state conf :acls (when
+ (Utils/isZkAuthenticationConfiguredStormServer
+ conf)
+ NIMBUS-ZK-ACLS))
:submit-lock (Object.)
+ :cred-update-lock (Object.)
:heartbeats-cache (atom {})
:downloaders (file-cache-map conf)
:uploaders (file-cache-map conf)
@@ -76,6 +84,8 @@
(halt-process! 20 "Error when processing an event")
))
:scheduler (mk-scheduler conf inimbus)
+ :id->sched-status (atom {})
+ :cred-renewers (AuthUtils/GetCredentialRenewers conf)
}))
(defn inbox [nimbus]
@@ -302,6 +312,7 @@
(defn- setup-storm-code [conf storm-id tmp-jar-location storm-conf topology]
(let [stormroot (master-stormdist-root conf storm-id)]
+ (log-message "nimbus file location:" stormroot)
(FileUtils/forceMkdir (File. stormroot))
(FileUtils/cleanDirectory (File. stormroot))
(setup-jar conf tmp-jar-location stormroot)
@@ -590,6 +601,7 @@
new-scheduler-assignments (.getAssignments cluster)
;; add more information to convert SchedulerAssignment to Assignment
new-topology->executor->node+port (compute-topology->executor->node+port new-scheduler-assignments)]
+ (reset! (:id->sched-status nimbus) (.getStatusMap cluster))
;; print some useful information.
(doseq [[topology-id executor->node+port] new-topology->executor->node+port
:let [old-executor->node+port (-> topology-id
@@ -663,6 +675,7 @@
topologies
scratch-topology-id)
+ topology->executor->node+port (merge (into {} (for [id assigned-topology-ids] {id nil})) topology->executor->node+port)
now-secs (current-time-secs)
@@ -725,7 +738,8 @@
(current-time-secs)
{:type topology-initial-status}
(storm-conf TOPOLOGY-WORKERS)
- num-executors))))
+ num-executors
+ (storm-conf TOPOLOGY-SUBMITTER-USER)))))
;; Master:
;; job submit:
@@ -745,6 +759,19 @@
(throw (AlreadyAliveException. (str storm-name " is already active"))))
))
+(defn check-authorization!
+ ([nimbus storm-name storm-conf operation context]
+ (let [aclHandler (:authorization-handler nimbus)
+ ctx (or context (ReqContext/context))
+ check-conf (if storm-conf storm-conf (if storm-name {TOPOLOGY-NAME storm-name}))]
+ (log-message "[req " (.requestID ctx) "] Access from: " (.remoteAddress ctx) " principal:" (.principal ctx) " op:" operation)
+ (if aclHandler
+ (if-not (.permit aclHandler ctx operation check-conf)
+ (throw (AuthorizationException. (str operation (if storm-name (str " on topology " storm-name)) " is not authorized")))
+ ))))
+ ([nimbus storm-name storm-conf operation]
+ (check-authorization! nimbus storm-name storm-conf operation (ReqContext/context))))
+
(defn code-ids [conf]
(-> conf
master-stormdist-root
@@ -830,6 +857,23 @@
(swap! (:heartbeats-cache nimbus) dissoc id))
))))
+(defn renew-credentials [nimbus]
+ (let [storm-cluster-state (:storm-cluster-state nimbus)
+ renewers (:cred-renewers nimbus)
+ update-lock (:cred-update-lock nimbus)
+ assigned-ids (set (.active-storms storm-cluster-state))]
+ (when-not (empty? assigned-ids)
+ (doseq [id assigned-ids]
+ (locking update-lock
+ (let [orig-creds (.credentials storm-cluster-state id nil)]
+ (if orig-creds
+ (let [new-creds (HashMap. orig-creds)]
+ (doseq [renewer renewers]
+ (log-message "Renewing Creds For " id " with " renewer))
+ (when-not (= orig-creds new-creds)
+ (.set-credentials! storm-cluster-state id new-creds)
+ )))))))))
+
(defn- file-older-than? [now seconds file]
(<= (+ (.lastModified file) (to-millis seconds)) (to-millis now)))
@@ -872,26 +916,63 @@
(throw (InvalidTopologyException.
("Topology name cannot be blank"))))))
-(defn- try-read-storm-conf [conf storm-id]
+;; We will only file at <Storm dist root>/<Topology ID>/<File>
+;; to be accessed via Thrift
+;; ex., storm-local/nimbus/stormdist/aa-1-1377104853/stormjar.jar
+(defn check-file-access [conf file-path]
+ (log-debug "check file access:" file-path)
+ (try
+ (if (not= (.getCanonicalFile (File. (master-stormdist-root conf)))
+ (-> (File. file-path) .getCanonicalFile .getParentFile .getParentFile))
+ (throw (AuthorizationException. (str "Invalid file path: " file-path))))
+ (catch Exception e
+ (throw (AuthorizationException. (str "Invalid file path: " file-path))))))
+
+(defn try-read-storm-conf [conf storm-id]
(try-cause
(read-storm-conf conf storm-id)
(catch FileNotFoundException e
- (throw (NotAliveException. storm-id)))
+ (throw (NotAliveException. (str storm-id))))
)
)
-(defn- try-read-storm-topology [conf storm-id]
+(defn try-read-storm-conf-from-name [conf storm-name nimbus]
+ (let [storm-cluster-state (:storm-cluster-state nimbus)
+ id (get-storm-id storm-cluster-state storm-name)]
+ (try-read-storm-conf conf id)))
+
+(defn try-read-storm-topology [conf storm-id]
(try-cause
(read-storm-topology conf storm-id)
(catch FileNotFoundException e
- (throw (NotAliveException. storm-id)))
+ (throw (NotAliveException. (str storm-id))))
)
)
+(defn validate-topology-size [topo-conf nimbus-conf topology]
+ (let [workers-count (get topo-conf TOPOLOGY-WORKERS)
+ workers-allowed (get nimbus-conf NIMBUS-SLOTS-PER-TOPOLOGY)
+ num-executors (->> (all-components topology) (map-val num-start-executors))
+ executors-count (reduce + (vals num-executors))
+ executors-allowed (get nimbus-conf NIMBUS-EXECUTORS-PER-TOPOLOGY)]
+ (when (and
+ (not (nil? executors-allowed))
+ (> executors-count executors-allowed))
+ (throw
+ (InvalidTopologyException.
+ (str "Failed to submit topology. Topology requests more than " executors-allowed " executors."))))
+ (when (and
+ (not (nil? workers-allowed))
+ (> workers-count workers-allowed))
+ (throw
+ (InvalidTopologyException.
+ (str "Failed to submit topology. Topology requests more than " workers-allowed " workers."))))))
+
(defserverfn service-handler [conf inimbus]
(.prepare inimbus conf (master-inimbus-dir conf))
(log-message "Starting Nimbus with conf " conf)
- (let [nimbus (nimbus-data conf inimbus)]
+ (let [nimbus (nimbus-data conf inimbus)
+ principal-to-local (AuthUtils/GetPrincipalToLocalPlugin conf)]
(.prepare ^backtype.storm.nimbus.ITopologyValidator (:validator nimbus) conf)
(cleanup-corrupt-topologies! nimbus)
(doseq [storm-id (.active-storms (:storm-cluster-state nimbus))]
@@ -912,6 +993,12 @@
(fn []
(clean-inbox (inbox nimbus) (conf NIMBUS-INBOX-JAR-EXPIRATION-SECS))
))
+ (schedule-recurring (:timer nimbus)
+ 0
+ (conf NIMBUS-CREDENTIAL-RENEW-FREQ-SECS)
+ (fn []
+ (renew-credentials nimbus)))
+
(reify Nimbus$Iface
(^void submitTopologyWithOpts
[this ^String storm-name ^String uploadedJarLocation ^String serializedConf ^StormTopology topology
@@ -919,6 +1006,7 @@
(try
(assert (not-nil? submitOptions))
(validate-topology-name! storm-name)
+ (check-authorization! nimbus storm-name nil "submitTopology")
(check-storm-active! nimbus storm-name false)
(let [topo-conf (from-json serializedConf)]
(try
@@ -931,21 +1019,44 @@
topology))
(swap! (:submitted-count nimbus) inc)
(let [storm-id (str storm-name "-" @(:submitted-count nimbus) "-" (current-time-secs))
- storm-conf (normalize-conf
+ credentials (.get_creds submitOptions)
+ credentials (when credentials (.get_creds credentials))
+ topo-conf (from-json serializedConf)
+ storm-conf-submitted (normalize-conf
conf
- (-> serializedConf
- from-json
- (assoc STORM-ID storm-id)
+ (-> topo-conf
+ (assoc STORM-ID storm-id)
(assoc TOPOLOGY-NAME storm-name))
topology)
+ req (ReqContext/context)
+ principal (.principal req)
+ submitter-principal (if principal (.toString principal))
+ submitter-user (.toLocal principal-to-local principal)
+ topo-acl (distinct (remove nil? (conj (.get storm-conf-submitted TOPOLOGY-USERS) submitter-principal, submitter-user)))
+ storm-conf (-> storm-conf-submitted
+ (assoc TOPOLOGY-SUBMITTER-PRINCIPAL (if submitter-principal submitter-principal ""))
+ (assoc TOPOLOGY-SUBMITTER-USER (if submitter-user submitter-user "")) ;Don't let the user set who we launch as
+ (assoc TOPOLOGY-USERS topo-acl)
+ (assoc STORM-ZOOKEEPER-SUPERACL (.get conf STORM-ZOOKEEPER-SUPERACL)))
+ storm-conf (if (Utils/isZkAuthenticationConfiguredStormServer conf)
+ storm-conf
+ (dissoc storm-conf STORM-ZOOKEEPER-TOPOLOGY-AUTH-SCHEME STORM-ZOOKEEPER-TOPOLOGY-AUTH-PAYLOAD))
total-storm-conf (merge conf storm-conf)
topology (normalize-topology total-storm-conf topology)
storm-cluster-state (:storm-cluster-state nimbus)]
+ (if (and (conf SUPERVISOR-RUN-WORKER-AS-USER) (or (nil? submitter-user) (.isEmpty (.trim submitter-user))))
+ (throw (AuthorizationException. "Could not determine the user to run this topology as.")))
(system-topology! total-storm-conf topology) ;; this validates the structure of the topology
+ (validate-topology-size topo-conf conf topology)
+ (when (and (Utils/isZkAuthenticationConfiguredStormServer conf)
+ (not (Utils/isZkAuthenticationConfiguredTopology storm-conf)))
+ (throw (IllegalArgumentException. "The cluster is configured for zookeeper authentication, but no payload was provided.")))
(log-message "Received topology submission for " storm-name " with conf " storm-conf)
;; lock protects against multiple topologies being submitted at once and
;; cleanup thread killing topology in b/w assignment and starting the topology
(locking (:submit-lock nimbus)
+ ;;cred-update-lock is not needed here because creds are being added for the first time.
+ (.set-credentials! storm-cluster-state storm-id credentials storm-conf)
(setup-storm-code conf storm-id uploadedJarLocation storm-conf topology)
(.setup-heartbeats! storm-cluster-state storm-id)
(let [thrift-status->kw-status {TopologyInitialStatus/INACTIVE :inactive
@@ -962,10 +1073,12 @@
(SubmitOptions. TopologyInitialStatus/ACTIVE)))
(^void killTopology [this ^String name]
- (.killTopologyWithOpts this name (KillOptions.)))
+ (.killTopologyWithOpts this name (KillOptions.)))
(^void killTopologyWithOpts [this ^String storm-name ^KillOptions options]
(check-storm-active! nimbus storm-name true)
+ (let [topology-conf (try-read-storm-conf-from-name conf storm-name nimbus)]
+ (check-authorization! nimbus storm-name topology-conf "killTopology"))
(let [wait-amt (if (.is_set_wait_secs options)
(.get_wait_secs options)
)]
@@ -974,6 +1087,8 @@
(^void rebalance [this ^String storm-name ^RebalanceOptions options]
(check-storm-active! nimbus storm-name true)
+ (let [topology-conf (try-read-storm-conf-from-name conf storm-name nimbus)]
+ (check-authorization! nimbus storm-name topology-conf "rebalance"))
(let [wait-amt (if (.is_set_wait_secs options)
(.get_wait_secs options))
num-workers (if (.is_set_num_workers options)
@@ -989,13 +1104,26 @@
))
(activate [this storm-name]
+ (let [topology-conf (try-read-storm-conf-from-name conf storm-name nimbus)]
+ (check-authorization! nimbus storm-name topology-conf "activate"))
(transition-name! nimbus storm-name :activate true)
)
(deactivate [this storm-name]
+ (let [topology-conf (try-read-storm-conf-from-name conf storm-name nimbus)]
+ (check-authorization! nimbus storm-name topology-conf "deactivate"))
(transition-name! nimbus storm-name :inactivate true))
+ (uploadNewCredentials [this storm-name credentials]
+ (let [storm-cluster-state (:storm-cluster-state nimbus)
+ storm-id (get-storm-id storm-cluster-state storm-name)
+ topology-conf (try-read-storm-conf conf storm-id)
+ creds (when credentials (.get_creds credentials))]
+ (check-authorization! nimbus storm-name topology-conf "uploadNewCredentials")
+ (locking (:cred-update-lock nimbus) (.set-credentials! storm-cluster-state storm-id creds topology-conf))))
+
(beginFileUpload [this]
+ (check-authorization! nimbus nil nil "fileUpload")
(let [fileloc (str (inbox nimbus) "/stormjar-" (uuid) ".jar")]
(.put (:uploaders nimbus)
fileloc
@@ -1005,6 +1133,7 @@
))
(^void uploadChunk [this ^String location ^ByteBuffer chunk]
+ (check-authorization! nimbus nil nil "fileUpload")
(let [uploaders (:uploaders nimbus)
^WritableByteChannel channel (.get uploaders location)]
(when-not channel
@@ -1015,6 +1144,7 @@
))
(^void finishFileUpload [this ^String location]
+ (check-authorization! nimbus nil nil "fileUpload")
(let [uploaders (:uploaders nimbus)
^WritableByteChannel channel (.get uploaders location)]
(when-not channel
@@ -1026,6 +1156,8 @@
))
(^String beginFileDownload [this ^String file]
+ (check-authorization! nimbus nil nil "fileDownload")
+ (check-file-access (:conf nimbus) file)
(let [is (BufferFileInputStream. file)
id (uuid)]
(.put (:downloaders nimbus) id is)
@@ -1033,6 +1165,7 @@
))
(^ByteBuffer downloadChunk [this ^String id]
+ (check-authorization! nimbus nil nil "fileDownload")
(let [downloaders (:downloaders nimbus)
^BufferFileInputStream is (.get downloaders id)]
(when-not is
@@ -1046,18 +1179,29 @@
)))
(^String getNimbusConf [this]
+ (check-authorization! nimbus nil nil "getNimbusConf")
(to-json (:conf nimbus)))
(^String getTopologyConf [this ^String id]
- (to-json (try-read-storm-conf conf id)))
+ (let [topology-conf (try-read-storm-conf conf id)
+ storm-name (topology-conf TOPOLOGY-NAME)]
+ (check-authorization! nimbus storm-name topology-conf "getTopologyConf")
+ (to-json topology-conf)))
(^StormTopology getTopology [this ^String id]
- (system-topology! (try-read-storm-conf conf id) (try-read-storm-topology conf id)))
+ (let [topology-conf (try-read-storm-conf conf id)
+ storm-name (topology-conf TOPOLOGY-NAME)]
+ (check-authorization! nimbus storm-name topology-conf "getTopology")
+ (system-topology! topology-conf (try-read-storm-topology conf id))))
(^StormTopology getUserTopology [this ^String id]
- (try-read-storm-topology conf id))
+ (let [topology-conf (try-read-storm-conf conf id)
+ storm-name (topology-conf TOPOLOGY-NAME)]
+ (check-authorization! nimbus storm-name topology-conf "getUserTopology")
+ (try-read-storm-topology topology-conf id)))
(^ClusterSummary getClusterInfo [this]
+ (check-authorization! nimbus nil nil "getClusterInfo")
(let [storm-cluster-state (:storm-cluster-state nimbus)
supervisor-infos (all-supervisor-info storm-cluster-state)
;; TODO: need to get the port info about supervisors...
@@ -1073,9 +1217,9 @@
))
nimbus-uptime ((:uptime nimbus))
bases (topology-bases storm-cluster-state)
- topology-summaries (dofor [[id base] bases]
- (let [assignment (.assignment-info storm-cluster-state id nil)]
- (TopologySummary. id
+ topology-summaries (dofor [[id base] bases :when base]
+ (let [assignment (.assignment-info storm-cluster-state id nil)
+ topo-summ (TopologySummary. id
(:storm-name base)
(->> (:executor->node+port assignment)
keys
@@ -1089,7 +1233,10 @@
set
count)
(time-delta (:launch-time-secs base))
- (extract-status-str base))
+ (extract-status-str base))]
+ (when-let [owner (:owner base)] (.set_owner topo-summ owner))
+ (when-let [sched-status (.get @(:id->sched-status nimbus) id)] (.set_sched_status topo-summ sched-status))
+ topo-summ
))]
(ClusterSummary. supervisor-summaries
nimbus-uptime
@@ -1098,8 +1245,14 @@
(^TopologyInfo getTopologyInfo [this ^String storm-id]
(let [storm-cluster-state (:storm-cluster-state nimbus)
- task->component (storm-task-info (try-read-storm-topology conf storm-id) (try-read-storm-conf conf storm-id))
+ topology-conf (try-read-storm-conf conf storm-id)
+ storm-name (topology-conf TOPOLOGY-NAME)
+ _ (check-authorization! nimbus storm-name topology-conf "getTopologyInfo")
+ task->component (storm-task-info (try-read-storm-topology conf storm-id) topology-conf)
base (.storm-base storm-cluster-state storm-id nil)
+ storm-name (if base (:storm-name base) (throw (NotAliveException. (str storm-id))))
+ launch-time-secs (if base (:launch-time-secs base) (throw (NotAliveException. (str storm-id))))
+ task->component (storm-task-info (try-read-storm-topology conf storm-id) topology-conf)
assignment (.assignment-info storm-cluster-state storm-id nil)
beats (.executor-beats storm-cluster-state storm-id (:executor->node+port assignment))
all-components (-> task->component reverse-map keys)
@@ -1120,14 +1273,16 @@
(nil-to-zero (:uptime heartbeat)))
(.set_stats stats))
))
- ]
- (TopologyInfo. storm-id
- (:storm-name base)
- (time-delta (:launch-time-secs base))
- executor-summaries
- (extract-status-str base)
- errors
- )
+ topo-info (TopologyInfo. storm-id
+ storm-name
+ (time-delta launch-time-secs)
+ executor-summaries
+ (extract-status-str base)
+ errors
+ )]
+ (when-let [owner (:owner base)] (.set_owner topo-info owner))
+ (when-let [sched-status (.get @(:id->sched-status nimbus) storm-id)] (.set_sched_status topo-info sched-status))
+ topo-info
))
Shutdownable
@@ -1146,16 +1301,13 @@
(defn launch-server! [conf nimbus]
(validate-distributed-mode! conf)
(let [service-handler (service-handler conf nimbus)
- options (-> (TNonblockingServerSocket. (int (conf NIMBUS-THRIFT-PORT)))
- (THsHaServer$Args.)
- (.workerThreads 64)
- (.protocolFactory (TBinaryProtocol$Factory. false true (conf NIMBUS-THRIFT-MAX-BUFFER-SIZE)))
- (.processor (Nimbus$Processor. service-handler))
- )
- server (THsHaServer. (do (set! (. options maxReadBufferBytes)(conf NIMBUS-THRIFT-MAX-BUFFER-SIZE)) options))]
+ ;;TODO need to honor NIMBUS-THRIFT-MAX-BUFFER-SIZE for different transports
+ server (ThriftServer. conf (Nimbus$Processor. service-handler)
+ ThriftConnectionType/NIMBUS)]
(.addShutdownHook (Runtime/getRuntime) (Thread. (fn [] (.shutdown service-handler) (.stop server))))
(log-message "Starting Nimbus server...")
- (.serve server)))
+ (.serve server)
+ service-handler))
;; distributed implementation
@@ -1175,7 +1327,10 @@
)
(defn -launch [nimbus]
- (launch-server! (read-storm-config) nimbus))
+ (let [conf (merge
+ (read-storm-config)
+ (read-yaml-config "storm-cluster-auth.yaml" false))]
+ (launch-server! conf nimbus)))
(defn standalone-nimbus []
(reify INimbus
http://git-wip-us.apache.org/repos/asf/incubator-storm/blob/fe5f41aa/storm-core/src/clj/backtype/storm/daemon/supervisor.clj
----------------------------------------------------------------------
diff --git a/storm-core/src/clj/backtype/storm/daemon/supervisor.clj b/storm-core/src/clj/backtype/storm/daemon/supervisor.clj
index 7566a79..1f8e7e1 100644
--- a/storm-core/src/clj/backtype/storm/daemon/supervisor.clj
+++ b/storm-core/src/clj/backtype/storm/daemon/supervisor.clj
@@ -14,10 +14,14 @@
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns backtype.storm.daemon.supervisor
+ (:import [java.io OutputStreamWriter BufferedWriter IOException])
(:import [backtype.storm.scheduler ISupervisor])
(:use [backtype.storm bootstrap])
(:use [backtype.storm.daemon common])
(:require [backtype.storm.daemon [worker :as worker]])
+ (:import [org.apache.zookeeper data.ACL ZooDefs$Ids ZooDefs$Perms])
+ (:import [org.yaml.snakeyaml Yaml]
+ [org.yaml.snakeyaml.constructor SafeConstructor])
(:gen-class
:methods [^{:static true} [launch [backtype.storm.scheduler.ISupervisor] void]]))
@@ -62,7 +66,7 @@
"Returns map from port to struct containing :storm-id and :executors"
[assignments-snapshot assignment-id]
(->> (dofor [sid (keys assignments-snapshot)] (read-my-executors assignments-snapshot sid assignment-id))
- (apply merge-with (fn [& ignored] (throw-runtime "Should not have multiple topologies assigned to one port")))))
+ (apply merge-with (fn [& params] (throw-runtime (str "Should not have multiple topologies assigned to one port " params))))))
(defn- read-storm-code-locations
[assignments-snapshot]
@@ -98,6 +102,18 @@
(= (disj (set (:executors worker-heartbeat)) Constants/SYSTEM_EXECUTOR_ID)
(set (:executors local-assignment))))))
+(let [dead-workers (atom #{})]
+ (defn get-dead-workers []
+ @dead-workers)
+ (defn add-dead-worker [worker]
+ (swap! dead-workers conj worker))
+ (defn remove-dead-worker [worker]
+ (swap! dead-workers disj worker)))
+
+(defn is-worker-hb-timed-out? [now hb conf]
+ (> (- now (:time-secs hb))
+ (conf SUPERVISOR-WORKER-TIMEOUT-SECS)))
+
(defn read-allocated-workers
"Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead (timed out or never wrote heartbeat)"
[supervisor assigned-executors now]
@@ -114,8 +130,11 @@
(or (not (contains? approved-ids id))
(not (matches-an-assignment? hb assigned-executors)))
:disallowed
- (> (- now (:time-secs hb))
- (conf SUPERVISOR-WORKER-TIMEOUT-SECS))
+ (or
+ (when (get (get-dead-workers) id)
+ (log-message "Worker Process " id " has died!")
+ true)
+ (is-worker-hb-timed-out? now hb conf))
:timed-out
true
:valid)]
@@ -151,35 +170,76 @@
(defn generate-supervisor-id []
(uuid))
-(defn try-cleanup-worker [conf id]
+(defnk worker-launcher [conf user args :environment {} :log-prefix nil :exit-code-callback nil]
+ (let [_ (when (clojure.string/blank? user)
+ (throw (java.lang.IllegalArgumentException.
+ "User cannot be blank when calling worker-launcher.")))
+ wl-initial (conf SUPERVISOR-WORKER-LAUNCHER)
+ storm-home (System/getProperty "storm.home")
+ wl (if wl-initial wl-initial (str storm-home "/bin/worker-launcher"))
+ command (concat [wl user] args)]
+ (log-message "Running as user:" user " command:" (pr-str command))
+ (launch-process command :environment environment :log-prefix log-prefix :exit-code-callback exit-code-callback)
+ ))
+
+(defnk worker-launcher-and-wait [conf user args :environment {} :log-prefix nil]
+ (let [process (worker-launcher conf user args :environment environment)]
+ (if log-prefix
+ (read-and-log-stream log-prefix (.getInputStream process)))
+ (try
+ (.waitFor process)
+ (catch InterruptedException e
+ (log-message log-prefix " interrupted.")))
+ (.exitValue process)))
+
+(defn try-cleanup-worker [conf id user]
(try
- (rmr (worker-heartbeats-root conf id))
- ;; this avoids a race condition with worker or subprocess writing pid around same time
- (rmpath (worker-pids-root conf id))
- (rmpath (worker-root conf id))
+ (if (.exists (File. (worker-root conf id)))
+ (do
+ (if (conf SUPERVISOR-RUN-WORKER-AS-USER)
+ (worker-launcher-and-wait conf user ["rmr" (worker-root conf id)] :log-prefix (str "rmr " id) )
+ (do
+ (rmr (worker-heartbeats-root conf id))
+ ;; this avoids a race condition with worker or subprocess writing pid around same time
+ (rmpath (worker-pids-root conf id))
+ (rmpath (worker-root conf id))))
+ (remove-worker-user! conf id)
+ (remove-dead-worker id)
+ ))
+ (catch IOException e
+ (log-warn-error e "Failed to cleanup worker " id ". Will retry later"))
(catch RuntimeException e
(log-warn-error e "Failed to cleanup worker " id ". Will retry later")
)
(catch java.io.FileNotFoundException e (log-message (.getMessage e)))
- (catch java.io.IOException e (log-message (.getMessage e)))
))
(defn shutdown-worker [supervisor id]
(log-message "Shutting down " (:supervisor-id supervisor) ":" id)
(let [conf (:conf supervisor)
pids (read-dir-contents (worker-pids-root conf id))
- thread-pid (@(:worker-thread-pids-atom supervisor) id)]
+ thread-pid (@(:worker-thread-pids-atom supervisor) id)
+ as-user (conf SUPERVISOR-RUN-WORKER-AS-USER)
+ user (get-worker-user conf id)]
(when thread-pid
(psim/kill-process thread-pid))
(doseq [pid pids]
- (ensure-process-killed! pid)
- (try
- (rmpath (worker-pid-path conf id pid))
- (catch Exception e)) ;; on windows, the supervisor may still holds the lock on the worker directory
- )
- (try-cleanup-worker conf id))
+ (if as-user
+ (worker-launcher-and-wait conf user ["signal" pid "9"] :log-prefix (str "kill -9 " pid))
+ (ensure-process-killed! pid))
+ (if as-user
+ (worker-launcher-and-wait conf user ["rmr" (worker-pid-path conf id pid)] :log-prefix (str "rmr for " pid))
+ (try
+ (rmpath (worker-pid-path conf id pid))
+ (catch Exception e)) ;; on windows, the supervisor may still holds the lock on the worker directory
+ ))
+ (try-cleanup-worker conf id user))
(log-message "Shut down " (:supervisor-id supervisor) ":" id))
+(def SUPERVISOR-ZK-ACLS
+ [(first ZooDefs$Ids/CREATOR_ALL_ACL)
+ (ACL. (bit-or ZooDefs$Perms/READ ZooDefs$Perms/CREATE) ZooDefs$Ids/ANYONE_ID_UNSAFE)])
+
(defn supervisor-data [conf shared-context ^ISupervisor isupervisor]
{:conf conf
:shared-context shared-context
@@ -187,7 +247,10 @@
:active (atom true)
:uptime (uptime-computer)
:worker-thread-pids-atom (atom {})
- :storm-cluster-state (cluster/mk-storm-cluster-state conf)
+ :storm-cluster-state (cluster/mk-storm-cluster-state conf :acls (when
+ (Utils/isZkAuthenticationConfiguredStormServer
+ conf)
+ SUPERVISOR-ZK-ACLS))
:local-state (supervisor-state conf)
:supervisor-id (.getSupervisorId isupervisor)
:assignment-id (.getAssignmentId isupervisor)
@@ -240,7 +303,8 @@
(shutdown-worker supervisor id)
))
(doseq [id (vals new-worker-ids)]
- (local-mkdirs (worker-pids-root conf id)))
+ (local-mkdirs (worker-pids-root conf id))
+ (local-mkdirs (worker-heartbeats-root conf id)))
(.put local-state LS-APPROVED-WORKERS
(merge
(select-keys (.get local-state LS-APPROVED-WORKERS)
@@ -422,8 +486,11 @@
(.shutdown supervisor)
)
-;; distributed implementation
+(defn setup-storm-code-dir [conf storm-conf dir]
+ (if (conf SUPERVISOR-RUN-WORKER-AS-USER)
+ (worker-launcher-and-wait conf (storm-conf TOPOLOGY-SUBMITTER-USER) ["code-dir" dir] :log-prefix (str "setup conf for " dir))))
+;; distributed implementation
(defmethod download-storm-code
:distributed [conf storm-id master-code-dir]
;; Downloading to permanent location is atomic
@@ -436,7 +503,31 @@
(Utils/downloadFromMaster conf (master-stormconf-path master-code-dir) (supervisor-stormconf-path tmproot))
(extract-dir-from-jar (supervisor-stormjar-path tmproot) RESOURCES-SUBDIR tmproot)
(FileUtils/moveDirectory (File. tmproot) (File. stormroot))
- ))
+ (setup-storm-code-dir conf (read-supervisor-storm-conf conf storm-id) stormroot)
+ ))
+
+(defn write-log-metadata-to-yaml-file! [storm-id port data conf]
+ (let [file (get-log-metadata-file storm-id port)]
+ ;;run worker as user needs the directory to have special permissions
+ ;; or it is insecure
+ (when (and (not (conf SUPERVISOR-RUN-WORKER-AS-USER))
+ (not (.exists (.getParentFile file))))
+ (.mkdirs (.getParentFile file)))
+ (let [writer (java.io.FileWriter. file)
+ yaml (Yaml.)]
+ (try
+ (.dump yaml data writer)
+ (finally
+ (.close writer))))))
+
+(defn write-log-metadata! [storm-conf user worker-id storm-id port conf]
+ (let [data {TOPOLOGY-SUBMITTER-USER user
+ "worker-id" worker-id
+ LOGS-USERS (sort (distinct (remove nil?
+ (concat
+ (storm-conf LOGS-USERS)
+ (storm-conf TOPOLOGY-USERS)))))}]
+ (write-log-metadata-to-yaml-file! storm-id port data conf)))
(defn jlp [stormroot conf]
(let [resource-root (str stormroot File/separator RESOURCES-SUBDIR)
@@ -445,11 +536,23 @@
arch-resource-root (str resource-root File/separator os "-" arch)]
(str arch-resource-root File/pathSeparator resource-root File/pathSeparator (conf JAVA-LIBRARY-PATH))))
-(defn- substitute-worker-childopts [value port]
- (let [sub-fn (fn [s] (.replaceAll s "%ID%" (str port)))]
- (if (list? value)
- (map sub-fn value)
- (-> value sub-fn (.split " ")))))
+(defn substitute-childopts
+ [childopts worker-id storm-id port]
+ (
+ let [replacement-map {"%ID%" (str port)
+ "%WORKER-ID%" (str worker-id)
+ "%STORM-ID%" (str storm-id)
+ "%WORKER-PORT%" (str port)}
+ sub-fn (fn [s]
+ (reduce (fn [string entry]
+ (apply clojure.string/replace string entry))
+ s replacement-map))]
+ (if-not (nil? childopts)
+ (if (sequential? childopts)
+ (map sub-fn childopts)
+ (-> childopts sub-fn (.split " ")))
+ nil)
+ ))
(defn java-cmd []
(let [java-home (.get (System/getenv) "JAVA_HOME")]
@@ -462,21 +565,25 @@
(defmethod launch-worker
:distributed [supervisor storm-id port worker-id]
(let [conf (:conf supervisor)
+ run-worker-as-user (conf SUPERVISOR-RUN-WORKER-AS-USER)
storm-home (System/getProperty "storm.home")
stormroot (supervisor-stormdist-root conf storm-id)
jlp (jlp stormroot conf)
stormjar (supervisor-stormjar-path stormroot)
storm-conf (read-supervisor-storm-conf conf storm-id)
classpath (add-to-classpath (current-classpath) [stormjar])
- worker-childopts (when-let [s (conf WORKER-CHILDOPTS)]
- (substitute-worker-childopts s port))
- topo-worker-childopts (when-let [s (storm-conf TOPOLOGY-WORKER-CHILDOPTS)]
- (substitute-worker-childopts s port))
- logfilename (str "worker-" port ".log")
+ top-gc-opts (storm-conf TOPOLOGY-WORKER-GC-CHILDOPTS)
+ gc-opts (substitute-childopts (if top-gc-opts top-gc-opts (conf WORKER-GC-CHILDOPTS)) worker-id storm-id port)
+ user (storm-conf TOPOLOGY-SUBMITTER-USER)
+ logfilename (logs-filename storm-id port)
+
+ worker-childopts (substitute-childopts (conf WORKER-CHILDOPTS) worker-id storm-id port)
+ topo-worker-childopts (substitute-childopts (storm-conf TOPOLOGY-WORKER-CHILDOPTS) worker-id storm-id port)
command (concat
[(java-cmd) "-server"]
worker-childopts
topo-worker-childopts
+ gc-opts
[(str "-Djava.library.path=" jlp)
(str "-Dlogfile.name=" logfilename)
(str "-Dstorm.home=" storm-home)
@@ -490,13 +597,21 @@
(:assignment-id supervisor)
port
worker-id])
- command (->> command (map str) (filter (complement empty?)))
- shell-cmd (->> command
- (map #(str \' (clojure.string/escape % {\' "\\'"}) \'))
- (clojure.string/join " "))]
- (log-message "Launching worker with command: " shell-cmd)
- (launch-process command :environment {"LD_LIBRARY_PATH" jlp})
- ))
+ command (->> command (map str) (filter (complement empty?)))]
+
+ (log-message "Launching worker with command: " (shell-cmd command))
+ (write-log-metadata! storm-conf user worker-id storm-id port conf)
+ (set-worker-user! conf worker-id user)
+ (let [log-prefix (str "Worker Process " worker-id)
+ callback (fn [exit-code]
+ (log-message log-prefix " exited with code: " exit-code)
+ (add-dead-worker worker-id))]
+ (remove-dead-worker worker-id)
+ (if run-worker-as-user
+ (let [worker-dir (worker-root conf worker-id)]
+ (worker-launcher conf user ["worker" worker-dir (write-script worker-dir command :environment {"LD_LIBRARY_PATH" jlp})] :log-prefix log-prefix :exit-code-callback callback))
+ (launch-process command :environment {"LD_LIBRARY_PATH" jlp} :log-prefix log-prefix :exit-code-callback callback)
+ ))))
;; local implementation
@@ -536,6 +651,7 @@
(:assignment-id supervisor)
port
worker-id)]
+ (set-worker-user! conf worker-id "")
(psim/register-process pid worker)
(swap! (:worker-thread-pids-atom supervisor) assoc worker-id pid)
))
http://git-wip-us.apache.org/repos/asf/incubator-storm/blob/fe5f41aa/storm-core/src/clj/backtype/storm/daemon/task.clj
----------------------------------------------------------------------
diff --git a/storm-core/src/clj/backtype/storm/daemon/task.clj b/storm-core/src/clj/backtype/storm/daemon/task.clj
index 3650150..6a61cea 100644
--- a/storm-core/src/clj/backtype/storm/daemon/task.clj
+++ b/storm-core/src/clj/backtype/storm/daemon/task.clj
@@ -126,12 +126,9 @@
emit-sampler (mk-stats-sampler storm-conf)
stream->component->grouper (:stream->component->grouper executor-data)
user-context (:user-context task-data)
- executor-stats (:stats executor-data)
- debug? (= true (storm-conf TOPOLOGY-DEBUG))]
+ executor-stats (:stats executor-data)]
(fn ([^Integer out-task-id ^String stream ^List values]
- (when debug?
- (log-message "Emitting direct: " out-task-id "; " component-id " " stream " " values))
(let [target-component (.getComponentId worker-context out-task-id)
component->grouping (get stream->component->grouper stream)
grouping (get component->grouping target-component)
@@ -148,8 +145,6 @@
(if out-task-id [out-task-id])
))
([^String stream ^List values]
- (when debug?
- (log-message "Emitting: " component-id " " stream " " values))
(let [out-tasks (ArrayList.)]
(fast-map-iter [[out-component grouper] (get stream->component->grouper stream)]
(when (= :direct grouper)