summaryrefslogtreecommitdiffstats
path: root/testsuite/systemtap.base/itrace.exp
blob: 89d488e29c5b3fb715288c2d3483781cec23813f (plain)
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
# itrace test

# Initialize variables
set exepath "[pwd]/ls_[pid]"

# Why check for 1000 instructions executed?  We can't know the actual
# number to look for, so we just look for a reasonable number that
# should work for all platforms.

set itrace_single1_script {
    global instrs = 0
    probe begin { printf("systemtap starting probe\n") }
    probe process("%s").insn
    {
        instrs += 1
    }
    probe end {
	printf("systemtap ending probe\n")
	if (instrs > 1000) {
	    printf("instrs > 1000 (%%d)\n", instrs)
	}
	else {
	    printf("instrs <= 1000 (%%d)\n", instrs)
	}
    }
}
set itrace_single1_script_output "instrs > 1000 \\(\[0-9\]\[0-9\]*\\)\r\n"

set itrace_single2_script {
    global instrs = 0, itrace_on = 0, start_timer = 0
    probe begin { start_timer = 1; printf("systemtap starting probe\n") }
    probe process("%s").insn if (itrace_on)
    {
        instrs += 1
	if (instrs == 5)
	    exit()
    }
    probe timer.ms(1) if (start_timer)
    {   
        itrace_on = 1
    }
    probe timer.ms(10) if (start_timer)
    {   
        itrace_on = 0
    }
    probe end { printf("systemtap ending probe\n")
	printf("itraced = %%d\n", instrs)
    }
}
set itrace_single2_script_output "itraced = 5\r\n"

set itrace_block1_script {
    global branches = 0
    probe begin
    {
        printf("systemtap starting probe\n")
    }
    probe process("%s").insn.block
    {
        branches += 1
        if (branches == 5)
                exit()
    }
    probe end { printf("systemtap ending probe\n")
          printf("itraced block mode = %%d\n", branches)
    }
}
set itrace_block1_script_output "itraced block mode = 5\r\n"

set itrace_block2_script {
    global instrs = 0, itrace_on = 0, start_timer = 0
    probe begin { start_timer = 1; printf("systemtap starting probe\n") }
    probe process("%s").insn.block if (itrace_on)
    {
        instrs += 1
	if (instrs == 5)
	    exit()
    }
    probe timer.ms(1) if (start_timer)
    {   
        itrace_on = 1
    }
    probe timer.ms(10) if (start_timer)
    {   
        itrace_on = 0
    }
    probe end { printf("systemtap ending probe\n")
	printf("itraced = %%d\n", instrs)
    }
}
set itrace_block2_script_output "itraced = 5\r\n"

set itrace_single_step_script {
    %{
    #include "ptrace_compatibility.h"
    %}

    function has_single_step() %{
        THIS->__retvalue = arch_has_single_step(); /* pure */
    %}

    probe begin {
        printf("has_single_step: %d\n", has_single_step())
        exit()
    }
}

set itrace_block_step_script {
    %{
    #include "ptrace_compatibility.h"
    %}

    function has_block_step() %{
        THIS->__retvalue = arch_has_block_step(); /* pure */
    %}

    probe begin {
        printf("has_block_step: %d\n", has_block_step())
        exit()
    }
}

proc stap_check_feature { test_name script feature } {
    set rc -1
    verbose -log "stap -g -e \"$script\""
    spawn stap -g -e "$script"
    expect {
	-timeout 60
	-re "^$feature: 0" { set rc 0; pass $test_name }
	-re "^$feature: 1" { set rc 1; pass $test_name }
	eof { fail "$test_name (eof)" }
	timeout { fail "$test_name (timeout)" }
    }
    catch {close}
    catch {wait}
    return $rc
}

# Set up our own copy of /bin/ls, to make testing for a particular
# executable easy.  We can't use 'ln' here, since we might be creating
# a cross-device link.  We can't use 'ln -s' here, since the kernel
# resolves the symbolic link and reports that /bin/ls is being
# exec'ed (instead of our local copy).
if {[catch {exec cp /bin/ls $exepath} res]} {
    fail "unable to copy /bin/ls: $res"
    return
}

# "load" generation function for stap_run.  It spawns our own copy of
# /bin/ls, waits 1 second, then kills it.
proc run_ls_1_sec {} {
    global exepath

    spawn $exepath
    set exe_id $spawn_id
    after 1000;
    exec kill -INT -[exp_pid -i $exe_id]
    return 0;
}

# figure out if this system supports single stepping (if we've got
# utrace and we're doing install testing)
set TEST_NAME "itrace single step check"
set single_step_p 0
if {![utrace_p]} {
    untested "$TEST_NAME : no kernel utrace support found"
} elseif {![installtest_p]} {
    untested $TEST_NAME
} else {
    set single_step_p [stap_check_feature $TEST_NAME \
		       $itrace_single_step_script "has_single_step"]
}

# figure out if this system supports block stepping (if we've got
# utrace and we're doing install testing)
set TEST_NAME "itrace block step check"
set block_step_p 0
if {![utrace_p]} {
    untested "$TEST_NAME : no kernel utrace support found"
} elseif {![installtest_p]} {
    untested $TEST_NAME
} else {
    set block_step_p [stap_check_feature $TEST_NAME \
		      $itrace_block_step_script "has_block_step"]
}

# Run the single step tests
set TEST_NAME "itrace_single1"
if {![utrace_p]} {
    untested "$TEST_NAME : no kernel utrace support found"
} elseif {![installtest_p]} {
    untested $TEST_NAME
} elseif {$single_step_p != 1} {
    xfail "$TEST_NAME : no kernel single step support"
} else {
    set script [format $itrace_single1_script $exepath]
    stap_run $TEST_NAME run_ls_1_sec $itrace_single1_script_output -e $script
}

set TEST_NAME "itrace_single2"
if {![utrace_p]} {
    untested "$TEST_NAME : no kernel utrace support found"
} elseif {![installtest_p]} {
    untested $TEST_NAME
} elseif {$single_step_p != 1} {
    xfail "$TEST_NAME : no kernel single step support"
} else {
    set script [format $itrace_single2_script $exepath]
    stap_run $TEST_NAME run_ls_1_sec $itrace_single2_script_output -e $script
}

# Run the block step tests
set TEST_NAME "itrace_block1"
if {![utrace_p]} {
    untested "$TEST_NAME : no kernel utrace support found"
} elseif {![installtest_p]} {
    untested $TEST_NAME
} elseif {$block_step_p != 1} {
    xfail "$TEST_NAME : no kernel block step support"
} else {
    set script [format $itrace_block1_script $exepath]
    stap_run $TEST_NAME run_ls_1_sec $itrace_block1_script_output -e $script
}

set TEST_NAME "itrace_block2"
if {![utrace_p]} {
    untested "$TEST_NAME : no kernel utrace support found"
} elseif {![installtest_p]} {
    untested $TEST_NAME
} elseif {$block_step_p != 1} {
    xfail "$TEST_NAME : no kernel block step support"
} else {
    set script [format $itrace_block2_script $exepath]
    stap_run $TEST_NAME run_ls_1_sec $itrace_block2_script_output -e $script
}

# Cleanup
exec rm -f $exepath
6' href='#n716'>716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
#!/usr/bin/python
# fedpkg - a script to interact with the Fedora Packaging system
#
# Copyright (C) 2009 Red Hat Inc.
# Author(s): Jesse Keating <jkeating@redhat.com>
# 
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.

import argparse
import pyfedpkg
import fedora_cert
import os
import sys
import getpass
import logging
import koji
import xmlrpclib
import time
import random
import string
import re
import hashlib
import textwrap

# Define packages which belong to specific secondary arches
# This is ugly and should go away.  A better way to do this is to have a list
# of secondary arches, and then check the spec file for ExclusiveArch that
# is one of the secondary arches, and handle it accordingly.
SECONDARY_ARCH_PKGS = {'sparc': ['silo', 'prtconf', 'lssbus', 'afbinit',
                                 'piggyback', 'xorg-x11-drv-sunbw2',
                                 'xorg-x11-drv-suncg14', 'xorg-x11-drv-suncg3',
                                 'xorg-x11-drv-suncg6', 'xorg-x11-drv-sunffb',
                                 'xorg-x11-drv-sunleo', 'xorg-x11-drv-suntcx'],
                       'ppc': ['ppc64-utils', 'yaboot'],
                       'arm': []}

# Add a log filter class
class StdoutFilter(logging.Filter):

    def filter(self, record):
        # If the record level is 20 (INFO) or lower, let it through
        return record.levelno <= logging.INFO

# Add a class stolen from /usr/bin/koji to watch tasks
# this was cut/pasted from koji, and then modified for local use.
# The formatting is koji style, not the stile of this file.  Do not use these
# functions as a style guide.
# This is fragile and hopefully will be replaced by a real kojiclient lib.
class TaskWatcher(object):

    def __init__(self,task_id,session,level=0,quiet=False):
        self.id = task_id
        self.session = session
        self.info = None
        self.level = level
        self.quiet = quiet

    #XXX - a bunch of this stuff needs to adapt to different tasks

    def str(self):
        if self.info:
            label = koji.taskLabel(self.info)
            return "%s%d %s" % ('  ' * self.level, self.id, label)
        else:
            return "%s%d" % ('  ' * self.level, self.id)

    def __str__(self):
        return self.str()

    def get_failure(self):
        """Print infomation about task completion"""
        if self.info['state'] != koji.TASK_STATES['FAILED']:
            return ''
        error = None
        try:
            result = self.session.getTaskResult(self.id)
        except (xmlrpclib.Fault,koji.GenericError),e:
            error = e
        if error is None:
            # print "%s: complete" % self.str()
            # We already reported this task as complete in update()
            return ''
        else:
            return '%s: %s' % (error.__class__.__name__, str(error).strip())

    def update(self):
        """Update info and log if needed.  Returns True on state change."""
        if self.is_done():
            # Already done, nothing else to report
            return False
        last = self.info
        self.info = self.session.getTaskInfo(self.id, request=True)
        if self.info is None:
            log.error("No such task id: %i" % self.id)
            sys.exit(1)
        state = self.info['state']
        if last:
            #compare and note status changes
            laststate = last['state']
            if laststate != state:
                log.info("%s: %s -> %s" % (self.str(),
                                           self.display_state(last),
                                           self.display_state(self.info)))
                return True
            return False
        else:
            # First time we're seeing this task, so just show the current state
            log.info("%s: %s" % (self.str(), self.display_state(self.info)))
            return False

    def is_done(self):
        if self.info is None:
            return False
        state = koji.TASK_STATES[self.info['state']]
        return (state in ['CLOSED','CANCELED','FAILED'])

    def is_success(self):
        if self.info is None:
            return False
        state = koji.TASK_STATES[self.info['state']]
        return (state == 'CLOSED')

    def display_state(self, info):
        # We can sometimes be passed a task that is not yet open, but
        # not finished either.  info would be none.
        if not info:
            return 'unknown'
        if info['state'] == koji.TASK_STATES['OPEN']:
            if info['host_id']:
                host = self.session.getHost(info['host_id'])
                return 'open (%s)' % host['name']
            else:
                return 'open'
        elif info['state'] == koji.TASK_STATES['FAILED']:
            return 'FAILED: %s' % self.get_failure()
        else:
            return koji.TASK_STATES[info['state']].lower()

# Add a simple function to print usage, for the 'help' command
def usage(args):
    parser.print_help()

# Define our stub functions
def _is_secondary(module):
    """Check a list to see if the package is a secondary arch package"""

    for arch in SECONDARY_ARCH_PKGS.keys():
        if module in SECONDARY_ARCH_PKGS[arch]:
            return arch
    return None

def _get_secondary_config(mymodule):
    """Return the right config for a given secondary arch"""

    arch = _is_secondary(mymodule.module)
    if arch:
        if arch == 'ppc' and mymodule.distvar == 'fedora' and \
           mymodule.distval < '13':
            return None
        return os.path.expanduser('~/.koji/%s-config' % arch)
    else:
        return None

def _display_tasklist_status(tasks):
    free = 0
    open = 0
    failed = 0
    done = 0
    for task_id in tasks.keys():
        status = tasks[task_id].info['state']
        if status == koji.TASK_STATES['FAILED']:
            failed += 1
        elif status == koji.TASK_STATES['CLOSED'] or status == koji.TASK_STATES['CANCELED']:
            done += 1
        elif status == koji.TASK_STATES['OPEN'] or status == koji.TASK_STATES['ASSIGNED']:
            open += 1
        elif status == koji.TASK_STATES['FREE']:
            free += 1
    log.info("  %d free  %d open  %d done  %d failed" % (free, open, done, failed))

def _display_task_results(tasks):
    for task in [task for task in tasks.values() if task.level == 0]:
        state = task.info['state']
        task_label = task.str()

        if state == koji.TASK_STATES['CLOSED']:
            log.info('%s completed successfully' % task_label)
        elif state == koji.TASK_STATES['FAILED']:
            log.info('%s failed' % task_label)
        elif state == koji.TASK_STATES['CANCELED']:
            log.info('%s was canceled' % task_label)
        else:
            # shouldn't happen
            log.info('%s has not completed' % task_label)

def _watch_koji_tasks(session, tasklist, quiet=False):
    if not tasklist:
        return
    log.info('Watching tasks (this may be safely interrupted)...')
    # Place holder for return value
    rv = 0
    try:
        tasks = {}
        for task_id in tasklist:
            tasks[task_id] = TaskWatcher(task_id, session, quiet=quiet)
        while True:
            all_done = True
            for task_id,task in tasks.items():
                changed = task.update()
                if not task.is_done():
                    all_done = False
                else:
                    if changed:
                        # task is done and state just changed
                        if not quiet:
                            _display_tasklist_status(tasks)
                    if not task.is_success():
                        rv = 1
                for child in session.getTaskChildren(task_id):
                    child_id = child['id']
                    if not child_id in tasks.keys():
                        tasks[child_id] = TaskWatcher(child_id, session, task.level + 1, quiet=quiet)
                        tasks[child_id].update()
                        # If we found new children, go through the list again,
                        # in case they have children also
                        all_done = False
            if all_done:
                if not quiet:
                    print
                    _display_task_results(tasks)
                break

            time.sleep(1)
    except (KeyboardInterrupt):
        if tasks:
            log.info(
"""\nTasks still running. You can continue to watch with the 'koji watch-task' command.
Running Tasks:
%s""" % '\n'.join(['%s: %s' % (t.str(), t.display_state(t.info))
                   for t in tasks.values() if not t.is_done()]))
        # /us/rbin/koji considers a ^c while tasks are running to be a
        # non-zero exit.  I don't quite agree, so I comment it out here.
        #rv = 1
    return rv

# Stole these three functions from /usr/bin/koji
def _format_size(size):
    if (size / 1073741824 >= 1):
        return "%0.2f GiB" % (size / 1073741824.0)
    if (size / 1048576 >= 1):
        return "%0.2f MiB" % (size / 1048576.0)
    if (size / 1024 >=1):
        return "%0.2f KiB" % (size / 1024.0)
    return "%0.2f B" % (size)

def _format_secs(t):
    h = t / 3600
    t = t % 3600
    m = t / 60
    s = t % 60
    return "%02d:%02d:%02d" % (h, m, s)

def _progress_callback(uploaded, total, piece, time, total_time):
    percent_done = float(uploaded)/float(total)
    percent_done_str = "%02d%%" % (percent_done * 100)
    data_done = _format_size(uploaded)
    elapsed = _format_secs(total_time)

    speed = "- B/sec"
    if (time):
        if (uploaded != total):
            speed = _format_size(float(piece)/float(time)) + "/sec"
        else:
            speed = _format_size(float(total)/float(total_time)) + "/sec"

    # write formated string and flush
    sys.stdout.write("[% -36s] % 4s % 8s % 10s % 14s\r" % ('='*(int(percent_done*36)), percent_done_str, elapsed, data_done, speed))
    sys.stdout.flush()

def build(args):
    # We may not actually nave an srpm arg if we come directly from the build task
    if hasattr(args, 'srpm') and args.srpm and not args.scratch:
        log.error('Non-scratch builds cannot be from srpms.')
        sys.exit(1)
    # Place holder for if we build with an uploaded srpm or not
    url = None
    # See if this is a chain or not
    chain = None
    if hasattr(args, 'chain'):
        chain = args.chain
    user = getuser(args.user)
    # Need to do something with BUILD_FLAGS or KOJI_FLAGS here for compat
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
    except pyfedpkg.FedpkgError, e:
        # This error needs a better print out
        log.error('Could not use module: %s' % e)
        sys.exit(1)
    kojiconfig = _get_secondary_config(mymodule)
    if args.target:
        mymodule.target = args.target
    try:
        mymodule.init_koji(user, kojiconfig)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not log into koji: %s' % e)
        sys.exit(1)
    # handle uploading the srpm if we got one
    if hasattr(args, 'srpm') and args.srpm:
        # Figure out if we want a verbose output or not
        callback = None
        if not args.q:
            callback = _progress_callback
        # define a unique path for this upload.  Stolen from /usr/bin/koji
        uniquepath = 'cli-build/%r.%s' % (time.time(),
                                         ''.join([random.choice(string.ascii_letters)
                                                 for i in range(8)]))
        # Should have a try here, not sure what errors we'll get yet though
        mymodule.koji_upload(args.srpm, uniquepath, callback=callback)
        if not args.q:
            # print an extra blank line due to callback oddity
            print('')
        url = '%s/%s' % (uniquepath, os.path.basename(args.srpm))
    # Should also try this, again not sure what errors to catch
    try:
        task_id = mymodule.build(args.skip_tag, args.scratch, args.background,
                                 url, chain)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not initiate build: %s' % e)
        sys.exit(1)
    # Now that we have the task ID we need to deal with it.
    if args.nowait:
        # Log out of the koji session
        mymodule.kojisession.logout()
        return
    # pass info off to our koji task watcher
    return _watch_koji_tasks(mymodule.kojisession, [task_id], quiet=args.q)

def chainbuild(args):
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not use module %s' % e)
        sys.exit(1)
    # make sure we don't try to chain ourself
    if mymodule.module in args.package:
        log.error('%s must not be in the chain' % mymodule.module)
        sys.exit(1)
    # make sure we didn't get an empty chain
    if args.package == [':']:
        log.error('Must provide at least one dependency build')
        sys.exit(1)
    # Break the chain up into sections
    urls = []
    build_set = []
    log.debug('Processing chain %s' % ' '.join(args.package))
    for component in args.package:
        if component == ':':
            # We've hit the end of a set, add the set as a unit to the
            # url list and reset the build_set.
            urls.append(build_set)
            log.debug('Created a build set: %s' % ' '.join(build_set))
            build_set = []
        else:
            # Figure out the scm url to build from package name
            try:
                hash = pyfedpkg.get_latest_commit(component)
                url = pyfedpkg.ANONGITURL % {'module':
                                             component} + '#%s' % hash
            except pyfedpkg.FedpkgError, e:
                log.error('Could not get a build url for %s: %s'
                          % (component, e))
                sys.exit(1)
            # If there are no ':' in the chain list, treat each object as an
            # individual chain
            if ':' in args.package:
                build_set.append(url)
            else:
                urls.append([url])
                log.debug('Created a build set: %s' % url)
    # Take care of the last build set if we have one
    if build_set:
        log.debug('Created a build set: %s' % ' '.join(build_set))
        urls.append(build_set)
    # pass it off to build
    args.chain = urls
    args.skip_tag = False
    args.scratch = False
    build(args)

def getuser(user=None):
    if user:
        return user
    else:
        # Doing a try doesn't really work since the fedora_cert library just
        # exits on error, but if that gets fixed this will work better.
        try:
            return fedora_cert.read_user_cert()
        except:
            log.debug('Could not read Fedora cert, using login name')
            return os.getlogin()


def check(args):
    # not implimented; Not planned
    log.warning('Not implimented yet, got %s' % args)

def clean(args):
    dry = False
    useignore = True
    if args.dry_run:
        dry = True
    if args.x:
        useignore = False
    try:
        return pyfedpkg.clean(dry, useignore)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not clean: %s' % e)
        sys.exit(1)

def clog(args):
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        return mymodule.clog()
    except pyfedpkg.FedpkgError, e:
        log.error('Could not generate clog: %s' % e)
        sys.exit(1)

def clone(args):
    user = None
    if not args.anonymous:
        # Doing a try doesn't really work since the fedora_cert library just
        # exits on error, but if that gets fixed this will work better.
        user = getuser(args.user)
    try:
        if args.branches:
            pyfedpkg.clone_with_dirs(args.module[0], user)
        else:
            pyfedpkg.clone(args.module[0], user, args.path, args.branch)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not clone: %s' % e)
        sys.exit(1)

def commit(args):
    mymodule = None
    if args.clog:
        try:
            mymodule = pyfedpkg.PackageModule(args.path)
            mymodule.clog()
        except pyfedpkg.FedpkgError, e:
            log.error('coult not create clog: %s' % e)
            sys.exit(1)
        args.file = os.path.abspath(os.path.join(args.path, 'clog'))
    try:
        pyfedpkg.commit(args.path, args.message, args.file, args.files)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not commit: %s' % e)
        sys.exit(1)
    if args.tag:
        try:
            if not mymodule:
                mymodule = pyfedpkg.PackageModule(args.path)
            tagname = mymodule.nvr
            pyfedpkg.add_tag(tagname, True, args.message, args.file)
        except pyfedpkg.FedpkgError, e:
            log.error('Coult not create a tag: %s' % e)
            sys.exit(1)
    if args.push:
        push(args)

def compile(args):
    arch = None
    short = False
    if args.arch:
        arch = args.arch
    if args.short_circuit:
        short = True
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        return mymodule.compile(arch=arch, short=short)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not compile: %s' % e)
        sys.exit(1)

def diff(args):
    try:
        return pyfedpkg.diff(args.path, args.cached, args.files)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not diff: %s' % e)
        sys.exit(1)

def export(args):
    # not implimented; not planned
    log.warning('Not implimented yet, got %s' % args)

def gimmespec(args):
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        print(mymodule.spec)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not get spec file: %s' % e)
        sys.exit(1)

def giturl(args):
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        print(mymodule.giturl())
    except pyfedpkg.FedpkgError, e:
        log.error('Could not get the giturl: %s' % e)
        sys.exit(1)

def import_srpm(args):
    # See if we need to create a module from scratch, and do so
    if args.create:
        log.warning('Not implimented yet.')
        sys.exit(0)
    if not args.create:
        try:
            uploadfiles = pyfedpkg.import_srpm(args.srpm, path=args.path)
            mymodule = pyfedpkg.PackageModule(args.path)
            mymodule.upload(uploadfiles, replace=True)
        except pyfedpkg.FedpkgError, e:
            log.error('Could not import srpm: %s' % e)
            sys.exit(1)
        # replace this system call with a proper diff target when it is
        # readys
        pyfedpkg.diff(args.path, cached=True)
        print('--------------------------------------------')
        print("New content staged and new sources uploaded.")
        print("Commit if happy or revert with: git reset --hard HEAD")
    return

def install(args):
    arch = None
    short = False
    if args.arch:
        arch = args.arch
    if args.short_circuit:
        short = True
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        return mymodule.install(arch=arch, short=short)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not install: %s' % e)
        sys.exit(1)

def lint(args):
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        return mymodule.lint(info)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not run rpmlint: %s' % e)
        sys.exit(1)

def local(args):
    arch = None
    if args.arch:
        arch = args.arch
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        if args.md5:
            return mymodule.local(arch=arch, hashtype='md5')
        else:
            return mymodule.local(arch=arch)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not build locally: %s' % e)
        sys.exit(1)

def mockbuild(args):
    # Pick up any mockargs from the env
    mockargs = []
    try:
        mockargs = os.environ['MOCKARGS'].split()
    except KeyError:
        # there were no args
        pass
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        return mymodule.mockbuild(mockargs)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not run mockbuild: %s' % e)
        sys.exit(1)

def new(args):
    try:
        print(pyfedpkg.new(args.path))
    except pyfedpkg.FedpkgError, e:
        log.error('Could not get new changes: %s' % e)
        sys.exit(1)

def new_sources(args):
    # Check to see if the files passed exist
    for file in args.files:
        if not os.path.exists(file):
            log.error('File does not exist: %s' % file)
            sys.exit(1)
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        mymodule.upload(args.files, replace=args.replace)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not upload new sources: %s' % e)
        sys.exit(1)
    print("Source upload succeeded. Don't forget to commit the sources file")

def patch(args):
    # not implimented
    log.warning('Not implimented yet, got %s' % args)

def prep(args):
    arch = None
    if args.arch:
        arch = args.arch
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        return mymodule.prep(arch=arch)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not prep: %s' % e)
        sys.exit(1)

def pull(args):
    try:
        pyfedpkg.pull(path=args.path)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not push: %s' % e)
        sys.exit(1)

def push(args):
    try:
        pyfedpkg.push(path=args.path)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not push: %s' % e)
        sys.exit(1)

def retire(args):
    try:
        pyfedpkg.retire(args.path, args.msg)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not retire package: %s' % e)
        sys.exit(1)
    if args.push:
        push()

def scratchbuild(args):
    # A scratch build is just a build with --scratch
    args.scratch = True
    args.skip_tag = False
    build(args)

def sources(args):
    try:
        pyfedpkg.sources(args.path, args.outdir)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not download sources: %s' % e)
        sys.exit(1)

def srpm(args):
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        pyfedpkg.sources(args.path)
        if args.md5:
            mymodule.srpm('md5')
        else:
            mymodule.srpm()
    except pyfedpkg.FedpkgError, e:
        log.error('Could not make an srpm: %s' % e)
        sys.exit(1)

def switch_branch(args):
    if args.branch:
        try:
            pyfedpkg.switch_branch(args.branch, args.path)
        except pyfedpkg.FedpkgError, e:
            log.error('Unable to switch to another branch: %s' % e)
            sys.exit(1)
    else:
        try:
            (locals, remotes) = pyfedpkg._list_branches(path=args.path)
        except pyfedpkg.FedpkgError, e:
            log.error('Unable to list branches: %s' % e)
            sys.exit(1)
        # This is some ugly stuff here, but trying to emulate
        # the way git branch looks
        locals = ['  %s  ' % branch for branch in locals]
        local_branch = pyfedpkg._find_branch(args.path)
        locals[locals.index('  %s  ' % local_branch)] = '* %s' % local_branch
        print('Locals:\n%s\nRemotes:\n  %s' %
              ('\n'.join(locals), '\n  '.join(remotes)))

def tag(args):
    if args.list:
        try:
            pyfedpkg.list_tag(args.tag)
        except pyfedpkg.FedpkgError, e:
            log.error('Could not create a list of the tag: %s' % e)
            sys.exit(1)
    elif args.delete:
        try:
            pyfedpkg.delete_tag(args.tag, args.path)
        except pyfedpkg.FedpkgError, e:
            log.error('Coult not delete tag: %s' % e)
            sys.exit(1)
    else:
        filename = args.file
        tagname = args.tag
        try:
            if not tagname or args.clog:
                mymodule = pyfedpkg.PackageModule(args.path)
                if not tagname:
                    tagname = mymodule.nvr
                if clog:
                    mymodule.clog()
                    filename = 'clog'
            pyfedpkg.add_tag(tagname, args.force, args.message, filename)
        except pyfedpkg.FedpkgError, e:
            log.error('Coult not create a tag: %s' % e)
            sys.exit(1)

def tagrequest(args):
    user = getuser(args.user)
    passwd = getpass.getpass('Password for %s: ' % user)

    if not args.desc:
        args.desc = raw_input('\nAdd a description to your request: ')

    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        mymodule.new_ticket(user, passwd, args.desc, args.build)
    except pyfedpkg.FedpkgError, e:
        print('Could not request a tag release: %s' % e)
        sys.exit(1)

def unusedfedpatches(args):
    # not implimented; not planned
    log.warning('Not implimented yet, got %s' % args)

def unusedpatches(args):
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
        unused = mymodule.unused_patches()
    except pyfedpkg.FedpkgError, e:
        log.error('Could not get unused patches: %s' % e)
        sys.exit(1)
    print('\n'.join(unused))

def update(args):
    """Submit a new update to bodhi"""
    user = getuser(args.user)
    mymodule = pyfedpkg.PackageModule(args.path)
    nvr = '%s-%s-%s' % (mymodule.module, mymodule.ver, mymodule.rel)
    template = """\
    [ %(nvr)s ]

    # bugfix, security, enhancement, newpackage (required)
    type=

    # testing, stable
    request=testing

    # Bug numbers: 1234,9876
    bugs=%(bugs)s

    # Description of your update
    notes=Here is where you
        give an explanation of
        your update.

    # Enable request automation based on the stable/unstable karma thresholds
    autokarma=True
    stable_karma=3
    unstable_karma=-3

    # Automatically close bugs when this marked as stable
    close_bugs=True

    # Suggest that users restart after update
    suggest_reboot=False\
    """

    bodhi_args = {'nvr': nvr, 'bugs': ''}

    # Extract bug numbers from the latest changelog entry
    mymodule.clog()
    clog = file('clog').read()
    bugs = re.findall(r'#([0-9]*)', clog)
    if bugs:
        bodhi_args['bugs'] = ','.join(bugs)

    template = textwrap.dedent(template) % bodhi_args

    # Calculate the hash of the unaltered template
    orig_hash = hashlib.new('sha1')
    orig_hash.update(template)
    orig_hash = orig_hash.hexdigest()

    # Write out the template
    out = file('bodhi.template', 'w')
    out.write(template)
    out.close()

    # Open the template in a text editor
    editor = os.getenv('EDITOR', 'vi')
    pyfedpkg._run_command([editor, 'bodhi.template'], shell=True)

    # If the template was changed, submit it to bodhi
    hash = pyfedpkg._hash_file('bodhi.template', 'sha1')
    if hash != orig_hash:
        cmd = ['bodhi', '--new', '--release', mymodule.branch, '--file',
               'bodhi.template', nvr, '--username', user]
        try:
            pyfedpkg._run_command(cmd, shell=True)
        except pyfedpkg.FedpkgError, e:
            log.error('Could not generate update request: %s' % e)
            sys.exit(1)
    else:
        log.info('Bodhi update aborted!')

    # Clean up
    os.unlink('bodhi.template')
    os.unlink('clog')


def verrel(args):
    try:
        mymodule = pyfedpkg.PackageModule(args.path)
    except pyfedpkg.FedpkgError, e:
        log.error('Could not get ver-rel: %s' % e)
        sys.exit(1)
    print('%s-%s-%s' % (mymodule.module, mymodule.ver, mymodule.rel))

# THe main code goes here
if __name__ == '__main__':
    # Create the parser object
    parser = argparse.ArgumentParser(description = 'Fedora Packaging utility',
                                     prog = 'fedpkg',
                                     epilog = "For detailed help pass " \
                                               "--help to a target")

    # Add top level arguments
    # Let somebody override the username found in fedora cert
    parser.add_argument('-u', '--user')
    # Let the user define which path to look at instead of pwd
    parser.add_argument('--path', default = os.getcwd(),
                    help='Directory to interact with instead of current dir')
    # Verbosity
    parser.add_argument('-v', action = 'store_true',
                        help = 'Run with verbose debug output')
    parser.add_argument('-q', action = 'store_true',
                        help = 'Run quietly only displaying errors')

    # Add a subparsers object to use for the actions
    subparsers = parser.add_subparsers(title = 'Targets')

    # Set up the various actions
    # Add help to -h and --help
    parser_help = subparsers.add_parser('help', help = 'Show usage')
    parser_help.set_defaults(command = usage)

    # Add a common build parser to be used as a parent
    parser_build_common = subparsers.add_parser('build_common',
                                                add_help = False)
    parser_build_common.add_argument('--nowait', action = 'store_true',
                                     default = False,
                                     help = "Don't wait on build")
    parser_build_common.add_argument('--target',
                                     default = None,
                                     help = 'Define koji target to build into')
    parser_build_common.add_argument('--background', action = 'store_true',
                                     default = False,
                                     help = 'Run the build at a lower priority')

    # build target
    parser_build = subparsers.add_parser('build',
                                         help = 'Request build',
                                         parents = [parser_build_common])
    parser_build.add_argument('--skip-tag', action = 'store_true',
                              default = False,
                              help = 'Do not attempt to tag package')
    parser_build.add_argument('--scratch', action = 'store_true',
                              default = False,
                              help = 'Perform a scratch build')
    parser_build.add_argument('--srpm',
                              help = 'Build from an srpm.  Requires --scratch')
    parser_build.set_defaults(command = build)

    # chain build
    parser_chainbuild = subparsers.add_parser('chain-build',
                help = 'Build current package in order with other packages',
                parents = [parser_build_common])
    parser_chainbuild.add_argument('package', nargs = '+',
                                   help = """
Build current package in order with other packages
example: fedpkg chain-build libwidget libgizmo
The current package is added to the end of the CHAIN list.
Colons (:) can be used in the CHAIN parameter to define groups of packages.
Packages in any single group will be built in parallel and all packages in
a group must build successfully and populate the repository before the next
group will begin building.  For example:
fedpkg chain-build libwidget libaselib : libgizmo :
will cause libwidget and libaselib to be built in parallel, followed by
libgizmo and then the currect directory package. If no groups are defined,
packages will be built sequentially.
""")
    parser_chainbuild.set_defaults(command = chainbuild)

    # check preps; not planned
    #parser_check = subparsers.add_parser('check',
    #                            help = 'Check test srpm preps on all arches')
    #parser_check.set_defaults(command = check)

    # clean things up
    parser_clean = subparsers.add_parser('clean',
                                         help = 'Remove untracked files')
    parser_clean.add_argument('--dry-run', '-n', action = 'store_true',
                              help = 'Perform a dry-run')
    parser_clean.add_argument('-x', action = 'store_true',
                              help = 'Do not follow .gitignore rules')
    parser_clean.set_defaults(command = clean)

    # Create a changelog stub
    parser_clog = subparsers.add_parser('clog',
                    help = 'Make a clog file containing top changelog entry')
    parser_clog.set_defaults(command = clog)

    # clone take some options, and then passes the rest on to git
    parser_clone = subparsers.add_parser('clone',
                                         help = 'Clone and checkout a module')
    # Allow an old style clone with subdirs for branches
    parser_clone.add_argument('--branches', '-B',
                action = 'store_true',
                help = 'Do an old style checkout with subdirs for branches')
    # provide a convenient way to get to a specific branch
    parser_clone.add_argument('--branch', '-b',
                              help = 'Check out a specific branch')
    # allow to clone without needing a account on the fedora buildsystem
    parser_clone.add_argument('--anonymous', '-a',
                              action = 'store_true',
                              help = 'Check out a branch anonymously')
    # store the module to be cloned
    parser_clone.add_argument('module', nargs = 1,
                              help = 'Name of the module to clone')
    parser_clone.set_defaults(command = clone)

    parser_co = subparsers.add_parser('co', parents = [parser_clone],
                                      conflict_handler = 'resolve',
                                      help = 'Alias for clone')
    parser_co.set_defaults(command = clone)
    # commit stuff
    parser_commit = subparsers.add_parser('commit',
                                          help = 'Commit changes')
    parser_commit.add_argument('-c', '--clog',
                               default = False,
                               action = 'store_true',
                               help = 'Generate the commit message from the Changelog section')
    parser_commit.add_argument('-t', '--tag',
                               default = False,
                               action = 'store_true',
                               help = 'Create a tag for this commit')
    parser_commit.add_argument('-m', '--message',
                               default = None,
                               help = 'Use the given <msg> as the commit message')
    parser_commit.add_argument('-F', '--file',
                               default = None,