Access SparkConf from the worker - apache-spark

Is there a way to get spark configurations from the worker (i.e. inside the closure of a map function). I tried using
SparkEnv.get().conf()
but it seems to not contain all the custom spark configs that I've set prior to creating SparkContext
EDIT:
Through SparkEnv I'm able to get default configurations set via spark-defaults.config but all confs I set explicitly through the setter method
SparkConf conf = new SparkConf()
conf.set("my.configuration.key", "myConfigValue")
SparkContext sc = new SparkContext(conf)
are not present in the SparkConf object I get through SparkEnv.get().conf()

SparkEnv is a part of the developer API and is not intended for external use.
You can simply create a broadcast variable, though.
val confBd = sc.broadcast(sc.getConf.getAll.toMap)
rdd.foreachPartition(_ => println(confBd.value.get("spark.driver.host")))

Related

SparkContext.setLogLevel("DEBUG") doesn't works in Cluster

I'm trying to control my Spark logs use
sc.setLogLevel("ERROR");
seems like it doesn't work in the cluster environment. Can anyone help?
public static JavaSparkContext getSparkContext(String appName, SparkConf conf) {
SparkSession spark = getSparkSession(appName, conf);
JavaSparkContext sc = new JavaSparkContext(spark.sparkContext());
sc.setLogLevel("WARN");
return sc;
}
To configure log levels, add the following options to your spark submit command:
'--conf "spark.driver.extraJavaOptions=-Dlog4j.configuration=custom-log4j.properties"'
'--conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=custom-log4j.properties"'
This assumes you have a file called custom-log4j.properties on the classpath. This log4j can then control the verbosity of spark's logging.

Register custom classes for Kryo serialization in Beam Spark runner

I have seen that Beam Spark runner uses BeamSparkRunnerRegistrator for kryo registration. Is there a way to register custom user classes as well?
There is a way to do so, but first, may I ask why you want to do this?
Generally speaking, Beam's Spark runner uses Beam coders to serialize user data.
We currently have a bug in which cached DStreams are being serialized using Kryo, and if the user classes are not Kryo serializable this fails. BEAM-2669. We are currently attempting to solve this issue.
If this is the issue you are facing you can currently workaround this by using Kryo's registrator. Is this the issue you are facing? or do you have a different reason for doing this, please let me know.
In any case, here is how you can provide your own custom JavaSparkContext instance to Beam's Spark runner by using SparkContextOptions
SparkConf conf = new SparkConf();
conf.set("spark.serializer", KryoSerializer.class.getName());
conf.set("spark.kryo.registrator", "my.custom.KryoRegistrator");
JavaSparkContext jsc = new JavaSparkContext(..., conf);
SparkContextOptions options = PipelineOptionsFactory.as(SparkContextOptions.class);
options.setRunner(SparkRunner.class);
options.setUsesProvidedSparkContext(true);
options.setProvidedSparkContext(jsc);
Pipeline p = Pipeline.create(options);
For more information see:
Beam Spark runner documentation
Example: ProvidedSparkContextTest.java
Create your own KryoRegistrator with this custom serializer
package Mypackage
class MyRegistrator extends KryoRegistrator {
override def registerClasses(kryo: Kryo) {
kryo.register(classOf[A], new CustomASerializer())
}}
Then, add configuration entry about it with your registrator's fully-qualified name, e.g. Mypackage.MyRegistrator:
val conf = new SparkConf()
conf.set("spark.kryo.registrator", "Mypackage.KryoRegistrator")
See documentation: Data Serialization Spark
If you don’t want to register your classes, Kryo serialization will still work, but it will have to store the full class name with each object, which is wasteful.

Spark 2.0: Redefining SparkSession params through GetOrCreate and NOT seeing changes in WebUI

I'm using Spark 2.0 with PySpark.
I am redefining SparkSession parameters through a GetOrCreate method that was introduced in 2.0:
This method first checks whether there is a valid global default SparkSession, and if yes, return that one. If no valid global default SparkSession exists, the method creates a new SparkSession and assigns the newly created SparkSession as the global default.
In case an existing SparkSession is returned, the config options specified in this builder will be applied to the existing SparkSession.
https://spark.apache.org/docs/2.0.1/api/python/pyspark.sql.html#pyspark.sql.SparkSession.Builder.getOrCreate
So far so good:
from pyspark import SparkConf
SparkConf().toDebugString()
'spark.app.name=pyspark-shell\nspark.master=local[2]\nspark.submit.deployMode=client'
spark.conf.get("spark.app.name")
'pyspark-shell'
Then I redefine SparkSession config with the promise to see the changes in WebUI
appName(name)
Sets a name for the application, which will be shown in the Spark web UI.
https://spark.apache.org/docs/2.0.1/api/python/pyspark.sql.html#pyspark.sql.SparkSession.Builder.appName
c = SparkConf()
(c
.setAppName("MyApp")
.setMaster("local")
.set("spark.driver.memory","1g")
)
from pyspark.sql import SparkSession
(SparkSession
.builder
.enableHiveSupport() # metastore, serdes, Hive udf
.config(conf=c)
.getOrCreate())
spark.conf.get("spark.app.name")
'MyApp'
Now, when I go to localhost:4040, I would expect to see MyApp as an app name.
However, I still see pyspark-shell application UI
Where am I wrong?
Thanks in advance!
I believe that documentation is a bit misleading here and when you work with Scala you actually see a warning like this:
... WARN SparkSession$Builder: Use an existing SparkSession, some configuration may not take effect.
It was more obvious prior to Spark 2.0 with clear separation between contexts:
SparkContext configuration cannot be modified on runtime. You have to stop existing context first.
SQLContext configuration can be modified on runtime.
spark.app.name, like many other options, is bound to SparkContext, and cannot be modified without stopping the context.
Reusing existing SparkContext / SparkSession
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
spark.conf.get("spark.sql.shuffle.partitions")
String = 200
val conf = new SparkConf()
.setAppName("foo")
.set("spark.sql.shuffle.partitions", "2001")
val spark = SparkSession.builder.config(conf).getOrCreate()
... WARN SparkSession$Builder: Use an existing SparkSession ...
spark: org.apache.spark.sql.SparkSession = ...
spark.conf.get("spark.sql.shuffle.partitions")
String = 2001
While spark.app.name config is updated:
spark.conf.get("spark.app.name")
String = foo
it doesn't affect SparkContext:
spark.sparkContext.appName
String = Spark shell
Stopping existing SparkContext / SparkSession
Now let's stop the session and repeat the process:
spark.stop
val spark = SparkSession.builder.config(conf).getOrCreate()
... WARN SparkContext: Use an existing SparkContext ...
spark: org.apache.spark.sql.SparkSession = ...
spark.sparkContext.appName
String = foo
Interestingly when we stop the session we still get a warning about using existing SparkContext, but you can check it is actually stopped.
I ran into the same problem and struggled with it for a long time, then find a simple solution:
spark.stop()
then build your new sparksession again

Spark uses only one core when using forEachRemaining

I'm still new to Spark. I wrote this code to parse large string list.
I had to use forEachRemaining because I had to initialize some non-serializable objects in each partition.
JavaRDD<String> lines=initRetriever();
lines.foreachPartition(iter->{
Obj1 obj1=initObj1()
MyStringParser parser=new MyStringParser(obj1);
iter.forEachRemaining(str->{
try {
parser.parse(str);
} catch (ParsingException e) {
e.printStackTrace();
}
});
System.out.print("all parsed");
obj1.close();
});
I believe Spark is all about parallelism. But this program uses only a single thread on my local machine. Did I do something wrong? Missing configuration? Or maybe the iter doesn't allow it to execute all in parallel.
EDIT
I have no configuration files for Spark.
That's how I initialize Spark
SparkConf conf = new SparkConf()
.setAppName(AbstractSparkImporter.class.getCanonicalName())
.setMaster("local");
I run it on IDE and using mvn:exec command.
As #Alberto-Bonsanto indicated, using local[*] triggers Spark to use all available threads. More info here.
SparkConf conf = new SparkConf()
.setAppName(AbstractSparkImporter.class.getCanonicalName())
.setMaster("local[*]");

Idiomatic way to create a spark context with a default master

Is there an idiomatic way to create a spark context, that if no other master is provided will default to some fall back master?
e.g.
new SparkContext(defaultMaster = "local[4]")
If I run this with let's say, spark-submit and specify a master as a CLI param, or via an env variable, it will use that, but if I run it without specifying anything, it will default to what I provided above.
Is there a built in way to achieve this? (I have workarounds but I was wondering if there is a common pattern for this behavior)
You can use the following:
val conf = new SparkConf()
conf.setIfMissing("spark.master", "local[4]")
val sc = new SparkContext(conf)
you can set the default master url in conf/spark-defaults.conf in the Spark directory
or
Use :
val conf = new SparkConf()
conf.setMaster("local[4]")
val sc = new SparkContext(conf)
And whenever you set master url using --master it overrides the default values.

Resources