DspDealeridRetarget.scala 10.2 KB
Newer Older
wang-jinfeng committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
package mobvista.dmp.datasource.dsp

import java.net.URI

import mobvista.dmp.common.{CommonMapReduce, CommonSparkJob}
import mobvista.prd.datasource.util.GsonUtil
import org.apache.commons.cli.{BasicParser, Options}
import org.apache.commons.lang.StringUtils
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.sql.{Row, SaveMode, SparkSession}

import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer


class DspDealeridRetarget extends CommonSparkJob with Serializable {


  def commandOptions(): Options = {
    val options = new Options()
    options.addOption("yyyymmdd", true, "yyyymmdd")
    options.addOption("output", true, "output")
    options.addOption("appFile",true,"appFile")
    options.addOption("coalesce", true, "coalesce")
    options
  }



  override protected def run(args: Array[String]): Int = {
    val parser = new BasicParser()
    val options = commandOptions()
    val commandLine = parser.parse(options, args)

    val coalesce = commandLine.getOptionValue("coalesce")
    val yyyymmdd = commandLine.getOptionValue("yyyymmdd")
    val output = commandLine.getOptionValue("output")
    val appFile = commandLine.getOptionValue("appFile")


    val spark = SparkSession
      .builder()
      .config("spark.rdd.compress", "true")
      .config("spark.sql.orc.filterPushdown", "true")
      .config("spark.io.compression.codec", "snappy")
      .config("spark.sql.warehouse.dir", "s3://mob-emr-test/spark-warehouse")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .enableHiveSupport()
      .getOrCreate()

    try {

      val iosAppInfoMap = spark.sparkContext.textFile(appFile).filter(_.contains("202004"))
        .map(_.split("\t")).filter(_.length>=2)
        .map(buildAppInfo(_))
        .collectAsMap()
      val iosAppInfoBC = spark.sparkContext.broadcast(iosAppInfoMap)


      val adrAppInfoMap = spark.sparkContext.textFile(appFile).filter(_.contains("com."))
        .map(_.split("\t")).filter(_.length>=2)
        .map(buildAppInfo(_))
        .collectAsMap()
      val adrAppInfoBC = spark.sparkContext.broadcast(adrAppInfoMap)


      FileSystem.get(new URI(s"s3://mob-emr-test"), spark.sparkContext.hadoopConfiguration).delete(new Path(output), true)

      import spark.implicits._

      var sql =
        s"""
           |select dealerid,idfa,gaid,exitid,country,platform
           | from dwh.etl_dsp_request_daily_hours where dt ='${yyyymmdd}' and exchanges='mopub' and dealerid !=''
        """.stripMargin
        val df= spark.sql(sql).filter(filterData _).rdd.map(parseMapData(iosAppInfoBC,adrAppInfoBC,_))

      sql =
        s"""
           |select ext3,idfa,googleadid gaid,ext5 exitid,countrycode country,os platform
           |from adn_dsp.log_adn_dsp_org_request_orc_hour where  concat(yr,mt,dt) ='${yyyymmdd}'
           |and exchanges='mopub'
        """.stripMargin

      val df_org= spark.sql(sql).filter(filterData _).rdd.map(parseMapOrgData(iosAppInfoBC,adrAppInfoBC,_))

     /*df.union(df_org).flatMap(l=> l).toDF("deviceid", "devicetype", "platform","packagename","country","dealerid")
        .createOrReplaceTempView("dsp_org_etl_hours")*/

      df.union(df_org).flatMap(l=> l).toDF("device_id", "device_type", "platform","packagename","country","dealerid")
        .createOrReplaceTempView("dsp_org_etl_hours")


    val sql4=
        """
          |select device_id,
          |device_type,
          |max(platform) platform,
          |concat_ws('#',collect_set(packagename)) package_name,
          |min(country) country,
          |concat_ws('#',collect_set(dealerid)) dealerids
          |from dsp_org_etl_hours
          |group by device_id,device_type
        """.stripMargin


     /* val sql4=
        """
          |select device_id, device_type, platform,packagename,country,dealerid
          |from dsp_org_etl_hours
        """.stripMargin*/

     spark.sql(sql4).coalesce(coalesce.toInt)
        .write
        .mode(SaveMode.Overwrite)
        .option("orc.compress", "zlib")
        .option("mapreduce.fileoutputcommitter.marksuccessfuljobs", false)
        .orc(output)

    } finally {
      if (spark != null) {
        spark.stop()
      }
    }
    0
  }

  def buildAppInfo(array: Array[String]): Tuple2[String, String] = {
    val dealerid = array(0)
    val pkgName = array(1)
    (dealerid,pkgName)
  }



  def genRes(iosAppInfoBC: Broadcast[collection.Map[String, String]],adrAppInfoBC: Broadcast[collection.Map[String, String]],dealeridsStr: String, idfa: String, gaid: String, platform: String, exitId: String, country: String): Iterator[(String, String, String, String, String,String)] = {
    val buffer = new ArrayBuffer[Tuple6[String,String,String,String,String,String]]()
    val dealerids = GsonUtil.String2JsonArray(dealeridsStr)
    var idfagaidmd5 =""
    var imei =""
    var imeimd5 = ""
    if(StringUtils.isNotBlank(exitId)){
      val devIds = splitFun(exitId, ",")
      if(devIds.length>= 6 ){
        if (StringUtils.isNotBlank(devIds(2)) && devIds(2).matches(CommonMapReduce.imeiMd5Ptn)) {
          idfagaidmd5 = devIds(2)
        }

        if (StringUtils.isNotBlank(devIds(4)) && devIds(4).matches(CommonMapReduce.imeiPtn) && StringUtils.isNotBlank(country) && "CN".equalsIgnoreCase(country)) {
          imei = devIds(4)
        }

        if (StringUtils.isNotBlank(devIds(5)) && devIds(5).matches(CommonMapReduce.imeiMd5Ptn) && StringUtils.isNotBlank(country) && "CN".equalsIgnoreCase(country)) {
          imeimd5 = devIds(5)
        }
      }
    }

    var deviceid=""
    var devicetype=""
    if("ios".equalsIgnoreCase(platform)){
      if(StringUtils.isNotBlank(idfa)){
        deviceid = idfa
        devicetype="idfa"
      }
      else if(StringUtils.isNotBlank(idfagaidmd5)){
        deviceid = idfagaidmd5
        devicetype="idfamd5"
      }
    }else if("android".equalsIgnoreCase(platform) && "CN".equalsIgnoreCase(country)){
      if(StringUtils.isNotBlank(imei)){
        deviceid = imei
        devicetype="imei"
      }
      else if(StringUtils.isNotBlank(imeimd5)){
        deviceid = imeimd5
        devicetype="imeimd5"
      }
    }else if("android".equalsIgnoreCase(platform) && !"CN".equalsIgnoreCase(country)){
      if(StringUtils.isNotBlank(gaid)){
        deviceid = gaid
        devicetype="gaid"
      }
      else if(StringUtils.isNotBlank(idfagaidmd5)){
        deviceid = idfagaidmd5
        devicetype="gaidmd5"
      }
    }

   dealerids.foreach(element =>{
     var pkgname:Option[String] =None
     if("ios".equalsIgnoreCase(platform)) {
        pkgname = iosAppInfoBC.value.get(element.getAsString)
     }else {
        pkgname = adrAppInfoBC.value.get(element.getAsString)
     }
     if(pkgname != None ){
        buffer += Tuple6(deviceid,devicetype, platform,pkgname.get,country, element.getAsString )
      }
   })

    buffer.toIterator
  }

  def parseMapOrgData(iosAppInfoBC: Broadcast[collection.Map[String, String]],adrAppInfoBC: Broadcast[collection.Map[String, String]], row: Row): Iterator[Tuple6[String,String,String,String,String,String]] = {

    val ext3 = row.getAs[String]("ext3")
    var dealeridsStr = ""
    var resStr = ""
      if(StringUtils.isNotBlank(ext3) && ext3.startsWith("{")){
      try{
        val testObj = GsonUtil.String2JsonObject(ext3)
        val dealids =  testObj.get("dealids")
        if(dealids != null && !dealids.isJsonNull){
          dealeridsStr = dealids.toString
        }
      } catch {
        case e: Exception =>{e.printStackTrace()}
      }
    }

    val idfa = row.getAs[String]("idfa")
    val gaid = row.getAs[String]("gaid")
    val platform = row.getAs[String]("platform")
    val exitId = row.getAs[String]("exitid")
    val country = row.getAs[String]("country")

    if(StringUtils.isNotBlank(dealeridsStr)){
      val dealeridDemo = dealeridsStr.replace("\\","")
      val len =dealeridDemo.length
      resStr = dealeridDemo.substring(1,len -1)
    }

    genRes(iosAppInfoBC,adrAppInfoBC,resStr,idfa,gaid,platform,exitId,country)
  }

  def parseMapData(iosAppInfoBC: Broadcast[collection.Map[String, String]],adrAppInfoBC: Broadcast[collection.Map[String, String]],row: Row): Iterator[Tuple6[String,String,String,String,String,String]] = {

    val dealerid = row.getAs[String]("dealerid")
    val idfa = row.getAs[String]("idfa")
    val gaid = row.getAs[String]("gaid")
    val platform = row.getAs[String]("platform")
    val exitId = row.getAs[String]("exitid")
    val country = row.getAs[String]("country")
    genRes(iosAppInfoBC,adrAppInfoBC,dealerid,idfa,gaid,platform,exitId,country)

  }





  def filterData(row: Row): Boolean = {

//  dealerid,idfa,gaid,exitid,country
    val idfa = row.getAs[String]("idfa")
    val gaid = row.getAs[String]("gaid")
    val platform = row.getAs[String]("platform")
    val exitId = row.getAs[String]("exitid")
    val country = row.getAs[String]("country")

    if (!"ios".equals(platform) && !"android".equals(platform)) {
      return false
    }

    var deviceId = ""
    if ("ios".equals(platform) && StringUtils.isNotBlank(idfa) && idfa.matches(didPtn) && !allZero.equals(idfa)) {
          deviceId = idfa
    } else if ("android".equals(platform) && StringUtils.isNotBlank(gaid) && gaid.matches(didPtn) && !allZero.equals(gaid) ) {
      deviceId = gaid
    }

    var idfagaidmd5 =""
    var imei =""
    var imeimd5 = ""
    if(StringUtils.isNotBlank(exitId)){
      val devIds = splitFun(exitId, ",")
      if(devIds.length>= 6 ){
        if (StringUtils.isNotBlank(devIds(2)) && devIds(2).matches(CommonMapReduce.imeiMd5Ptn)) {
          idfagaidmd5 = devIds(2)
        }

        if (StringUtils.isNotBlank(devIds(4)) && devIds(4).matches(CommonMapReduce.imeiPtn) && StringUtils.isNotBlank(country) && "CN".equalsIgnoreCase(country)) {
          imei = devIds(4)
        }

        if (StringUtils.isNotBlank(devIds(5)) && devIds(5).matches(CommonMapReduce.imeiMd5Ptn) && StringUtils.isNotBlank(country) && "CN".equalsIgnoreCase(country)) {
          imeimd5 = devIds(5)
        }
      }
    }

    if (StringUtils.isBlank(deviceId) && StringUtils.isBlank(imei) && StringUtils.isBlank(imeimd5) && StringUtils.isBlank(idfagaidmd5)) {
      return false
    }
    true
  }
}

object DspDealeridRetarget {
  def main(args: Array[String]): Unit = {
    new DspDealeridRetarget().run(args)
  }
}