author Gregg Lind <glind@mozilla.com>
Thu, 31 Jul 2014 09:07:32 -0500
changeset 1035 5284ac662ddbb4ef94e973959da1f084cfec303e
parent 1013 e2df65bdd35db9aee346ad16466e3eb26947c0b0
permissions -rw-r--r--
Fabfile updated to new hosts and paths for "push" action.

import test_valid
from ConfigParser import ConfigParser
import errno
import json
import os
import os.path
import sys

from fabric.api import task, sudo, run, local, lcd, cd, env,hosts
from fabric.contrib.console import confirm

def mkdir_p(path):
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
        else: raise

# TODO:  this should list all profiles if called without argument
def find_profile_dir(name):
    Given the name of a Firefox profile, attempts to find the absolute
    path to its directory.  If it can't be found, None is returned.

    base_path = None
    if sys.platform == "darwin":
        base_path = os.path.expanduser(
            "~/Library/Application Support/Firefox/"
    elif sys.platform.startswith("win"):
        # TODO: This only works on 2000/XP/Vista, not 98/Me.
        appdata = os.environ["APPDATA"]
        base_path = os.path.join(appdata, "Mozilla\\Firefox")
    elif sys.platform == "cygwin":
        appdata = os.environ["APPDATA"]
        base_path = os.path.join(appdata, "Mozilla\\Firefox")
        base_path = os.path.expanduser("~/.mozilla/firefox/")
    inifile = os.path.join(base_path, "profiles.ini")
    config = ConfigParser()
    profiles = [section for section in config.sections()
                if section.startswith("Profile")]
    for profile in profiles:
        if config.get(profile, "Name") == name:
            # TODO: Look at IsRelative?
            path = config.get(profile, "Path")
            if not os.path.isabs(path):
                path = os.path.join(base_path, path)
            return path
    return None

def profile(string='default'):
    """ print the path to a profile.  call:  fab profile:profile_name"""
    print find_profile_dir(string)

def simplesurvey(url="",name="",summary="",fn="",minroll='1',maxroll='2'):
    """ create a simple survey



    t = """
"use strict";

exports.surveyInfo = {{
  surveyId: "{surveyId}",
  surveyName: "{name}",
  surveyUrl: "{url}",
  summary: {summary},
  thumbnail: "https://testpilot.mozillalabs.com/testcases/pilot-survey-thumbnail.png",
  randomDeployment: {{
    minRoll: {minroll},
    maxRoll: {maxroll},
    rolloutCode: "{surveyId}"
    surveyId = name_to_id(name)
    if not fn:
        fn = os.path.join(surveyId,surveyId + ".js")

    with open(fn,'w') as fh:
        print "# writing to: " + fn
        print >> fh, t.format(url=url,surveyId=surveyId,name=(name or surveyId),
        print """
    # edit: {fn}
    # then:
    fab package:{surveyId}""".format(**locals())

# TODO:  tree isn't a built-in...
def clear(profile):
    """ clear:profile.  removes downloaded experiments, logs, manifests from profile <profile>"""
    p = find_profile_dir(profile)
    d = "%s/TestPilotExperimentFiles" % p
    local('rm -rf "%s"/TestPilotErrorLog.log' % p)
    local('rm -rf "%s"/*' % (d,))
    local('tree "%s"' % (d,))

def push():
    sudo hg pull;  call:  fab push -u user.name
    if confirm("You did 'hg ci; hg pull; hg up; hg push' right?"):
        if confirm("You did change the sample size and turn of debugging, right?"):
            with cd("/data/www/testpilotweb/"):
                sudo("hg pull")
                result = sudo("hg tip")
                print "###### hg tip #####"
                print result
                if confirm("Upgrade to that tip?"):
                    sudo("hg update")

def rollback(rev_or_id):
    """ rollback upstream?"""

def guess_name(path,extension='.js'):
    files = os.listdir(path)
    print files
    guesses = [x for x in files if x.endswith(extension)]
    if len(guesses) == 1:
        return guesses[0]
        return None

def replace_in_json(name,newjson,manifest):
        name:  name of the study to match/replace
        newjson:  that studies json
        manifest:  the whole old shebang

        manifest, which replaces the orig (gross!)
        TODO, decide this for real.

    print name
    for k,v in manifest.iteritems():
        for ii,study in enumerate(v):
            cand = study.get('default',{}).get('name',None)
            if cand == name:
                manifest[k][ii] = newjson
                return manifest

    # else fall back...
    return manifest

def package(path,name=None,jsonfile=None):
    """ package:path,name,jsonfile.  jar, sign, and dump the snippet.  assumes one .js file -> jar.  path from root

        path: dir containing code.
        name: name of the study, if not, it gets the base of the js file
        jsonfile:  if there, replace the json with the created one.
    # be wary, lcd only changes how local and sudo and such are called.  the path
    # is still really the caller path.

    studyfile = guess_name(path) or os.path.split(path)[-1]
    with lcd(path):
        if studyfile:
            if studyfile.endswith('.js'):
                base = studyfile[:-3]
                base = studyfile

            if not name:

            # for unclear reasons, old formating was messing up bash on windows.
            print local('jar -cvf %s.jar *' % (base),capture=True)
            # this is a place where we really want '/'... urls!
            ini("/".join([path,base+ ".jar"]),name=name,studyfile=base + ".js")
            print "unable to guess name for packaging."

    if jsonfile:
        D = json.load(file(jsonfile))
        newjson = ini('/'.join([path,base+ ".jar"]),name=name,studyfile=base + ".js", prints=False)
        D =replace_in_json(name,newjson,D)
        print "revising json!"

import hashlib

def sign(fn):
    """ sign a file """
    # 'rb', for windows!
    with open(fn,'rb') as fh:
        return hashlib.sha256(fh.read()).hexdigest()

def print_sign(fn):
    print sign(fn)

def ini(path,name=None,studyfile=None,prints=True):
    """ path,name,studyfile.  ini snippet

    {"name": "exploring_satisfaction_survey_v2",
     "jarfile": "exploring_satisfaction_survey//exploring_satisfaction_survey.jar",
     "studyfile": "exploring_satisfaction_survey_v2.js",
     "hash": "59a28d941c24ff8ac55c632f0b65aece29de03dc858ff4b53a9ee71deab34ebb"
    if studyfile is None:
        studyfile=os.path.splitext(studyfile)[0] + ".js"
    if name is None:
        name = studyfile
    d = dict(name=name,jarfile=jarfile,studyfile=studyfile,hash=hash)
    if prints:
        print json.dumps({"new_experiments":[{'default':d}]},indent=2)
        return {'default':d}

def fakejson():

def name_to_id(name):
    return name.strip().lower().replace(" ","_")

def _test_valid(*args):

exports.surveyInfo = {
  surveyId: "firefox_upgrade_survey",
  surveyName: "Firefox Upgrade Survey",
  surveyUrl: "http://www.surveygizmo.com/s3/569257/TestPilot-Firefox-Upgrade-Survey",
  summary: "If you see this survey, most likely you are using Firefox 3.6 currently.  There is also a completely new version of Firefox which was released in March this year. Through this survey, We're interested to understand why you have not upgraded so that we can better meet your needs in our future products. ",
  thumbnail: "https://testpilot.mozillalabs.com/testcases/pilot-survey-thumbnail.png",

  runOrNotFunc: function() {
    let Application = Cc["@mozilla.org/fuel/application;1"]
    let versionComparator = Cc["@mozilla.org/xpcom/version-comparator;1"]
    let ver = Application.version;
    if( versionComparator.compare(ver, "3.6")>=0 && versionComparator.compare(ver, "3.7")<0 )
        return true;
        return false;

## a sample session.
NICE="Firefox Apps Usage Survey"
mkdir testcases/$NAME && \
cd testcases/$NAME
cat << DONE > $NAME.js
exports.surveyInfo = {
  surveyId: "$NAME",
  surveyName: "$NICE",
  surveyUrl: "http://qsurvey.mozilla.com/s3/apps_tp",
  summary: "Mozilla is currently exploring an apps initiaitive that aims to make more apps available across more devices. We would love your help with a brief survey to understand how you currently use apps. Thanks for helping us make the Web better.",
  thumbnail: "https://testpilot.mozillalabs.com/testcases/pilot-survey-thumbnail.png",

  randomDeployment: {
    maxRoll: 0,
    minRoll: 19,
    rolloutCode: "sample1",

  runOrNotFunc: function() {
    let Application = Cc["@mozilla.org/fuel/application;1"]
    let versionComparator = Cc["@mozilla.org/xpcom/version-comparator;1"]
    let ver = Application.version;
    /* this is the sort of thing you can use to decide who gets to run it.
    if( versionComparator.compare(ver, "3.6")>=0 && versionComparator.compare(ver, "3.7")<0 )
        return true;
        return false; */

    return true;

# jar and sign
jar -cf $NAME.jar $NAME.js
SIGN=`python ~/testpilot/codesigning/signer.py $NAME.jar | awk '{print $NF}'`

cat <<DONE
    {"name": "$NICE",
     "jarfile": "$NAME/$NAME.jar",
     "studyfile": "$NAME.js",
     "hash": "$SIGN"
echo "^ append this into ../index-dev.json  'new_experiments'"

hg add $NAME.jar $NAME.js ../index-dev.json
hg commit
hg push
ssh lm-app-testpilot01.labs.mozilla.org
cd /var/www/testcases
sudo hg pull -u

rm -rf "$F"
mkdir $F
cp $I/index-fake.json $F/index.json
cp $I/broken-extensions/broken-extensions-survey.jar $F/