fabfile.py
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):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            pass
        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")
    else:
        base_path = os.path.expanduser("~/.mozilla/firefox/")
    inifile = os.path.join(base_path, "profiles.ini")
    config = ConfigParser()
    config.read(inifile)
    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

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

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

    usage:

    """

    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}"
  }}
}};
""".strip()
    surveyId = name_to_id(name)
    if not fn:
        fn = os.path.join(surveyId,surveyId + ".js")

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


# TODO:  tree isn't a built-in...
@task
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,))

@task
@hosts(['testpilot1.webapp.scl3.mozilla.com'])
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):
    pass
    """ 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]
    else:
        return None

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

    Returns:
        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...
    manifest.setdefault('new_experiments',[])
    manifest['new_experiments'].append(newjson)
    return manifest


@task
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

    Args:
        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]
            else:
                base = studyfile

            if not name:
                name=base

            # 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")
        else:
            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!"
        json.dump(D,open(jsonfile,'w'),indent=2)

import hashlib


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

@task(alias='sign')
def print_sign(fn):
    print sign(fn)

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

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

def fakejson():
    pass

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

@task(alias="test_valid")
def _test_valid(*args):
    test_valid.main(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"]
                      .getService(Ci.fuelIApplication);
    let versionComparator = Cc["@mozilla.org/xpcom/version-comparator;1"]
                            .getService(Ci.nsIVersionComparator);
    let ver = Application.version;
    if( versionComparator.compare(ver, "3.6")>=0 && versionComparator.compare(ver, "3.7")<0 )
        return true;
    else
        return false;
  }
};


## a sample session.
pwd
NAME="firefox_apps_usage_survey"
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"]
                      .getService(Ci.fuelIApplication);
    let versionComparator = Cc["@mozilla.org/xpcom/version-comparator;1"]
                            .getService(Ci.nsIVersionComparator);
    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;
    else
        return false; */

    return true;
  }
};
DONE

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

cat <<DONE
  {"default":
    {"name": "$NICE",
     "jarfile": "$NAME/$NAME.jar",
     "studyfile": "$NAME.js",
     "hash": "$SIGN"
    }
  },
DONE
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



F=TestPilotExperimentFiles
rm -rf "$F"
I=~/hgs/testpilotweb/testcases/
mkdir $F
cp $I/index-fake.json $F/index.json
cp $I/broken-extensions/broken-extensions-survey.jar $F/




"""