source: DCWoRMS/branches/coolemall/src/simulator/DCWormsUsers.java @ 1299

Revision 1299, 10.8 KB checked in by wojtekp, 11 years ago (diff)
  • Property svn:mime-type set to text/plain
Line 
1package simulator;
2
3import dcworms.schedframe.scheduling.utils.JobDescription;
4import dcworms.schedframe.scheduling.utils.TaskDescription;
5import eduni.simjava.Sim_event;
6import eduni.simjava.Sim_system;
7import gridsim.GridSim;
8import gridsim.GridSimTags;
9import gridsim.IO_data;
10import gridsim.dcworms.DCWormsTags;
11import gridsim.net.InfoPacket;
12
13import java.util.ArrayList;
14import java.util.HashSet;
15import java.util.Iterator;
16import java.util.List;
17import java.util.Map;
18import java.util.Set;
19import java.util.TreeMap;
20
21import org.apache.commons.logging.Log;
22import org.apache.commons.logging.LogFactory;
23import org.joda.time.DateTime;
24
25import qcg.shared.constants.BrokerConstants;
26import schedframe.scheduling.tasks.Job;
27import schedframe.scheduling.tasks.JobInterface;
28import schedframe.scheduling.tasks.Task;
29import schedframe.scheduling.tasks.TaskInterface;
30import simulator.utils.XsltTransformations;
31import simulator.workload.WorkloadLoader;
32
33public class DCWormsUsers extends GridSim implements GenericUser {
34
35        /**A job generator, which produces jobs and tasks. These jobs are then sent by this entity */
36        protected WorkloadLoader workloadLoader;
37       
38        /** The name of the entity, to which the created tasks will be sent */
39        protected String destName;
40       
41        /** Indicates, that all tasks that returned to this object are finished */
42        protected boolean allTasksAreFinished;
43       
44        /** Stores the list of jobs, that have been returned to this object */
45        protected List<JobInterface<?>> returnedJobs;
46        protected Set<String> sendJobsIds;
47        protected Set<String> returnedJobsIds;
48       
49        protected long submissionStartTime = Long.MAX_VALUE;
50       
51        protected XsltTransformations xsltTransformer;
52       
53        /**
54         * Indicates, that an error has occurred - it is used for debug purposes
55         */
56        protected boolean error;
57       
58        private static Log log = LogFactory.getLog(DCWormsUsers.class);
59       
60        /**
61         * Constructs the users object with the given parameters
62         * @param name the name of the users entity (must be unique across all entities in the whole simulation)
63         * @param destinationName the name of the entity, to which the created tasks will be sent
64         * @param jobGenerator the job generator, which produces jobs and tasks, that will be sent by this class
65         * @throws Exception if any occurs (see {@link GridSim#GridSim(String, double)})
66         */
67        public DCWormsUsers(String name, String destinationName, WorkloadLoader workload) throws Exception {
68                super(name, DCWormsConstants.DEFAULT_BAUD_RATE);
69                this.workloadLoader = workload;
70                destName = destinationName;
71                allTasksAreFinished = true;
72                error = false;
73               
74                sendJobsIds = new HashSet<String>();
75                returnedJobsIds = new HashSet<String>();
76                returnedJobs = new ArrayList<JobInterface<?>>();
77                this.xsltTransformer = new XsltTransformations();
78        }
79
80        @Override
81        public void body() {
82                if(workloadLoader != null){
83                        sendJobs();
84                        collectJobs(); 
85                } else {
86                        submissionStartTime = 0;
87                }
88
89                //GridSim dependent code for shutting down the simulation
90                shutdownGridStatisticsEntity();
91                terminateIOEntities();
92                shutdownUserEntity();
93        }
94
95        /**
96         * Collects the jobs sent to broker(s)
97         */
98        protected void collectJobs() {
99                final int FACTOR = Math.min(100, workloadLoader.getTaskCount() > 0 ? workloadLoader.getTaskCount() : 1); //the refresh rate of the gauge: at most 10 times
100                final int denominator = workloadLoader.getTaskCount() / FACTOR;
101                allTasksAreFinished = true;
102                int counter = 0;
103                int oldRemeinder = 0;
104                boolean hundredPercent = false;
105               
106                Sim_event ev = new Sim_event();
107                sim_get_next(ev);
108                while (Sim_system.running()) {
109                        switch (ev.get_tag()) {
110                        case GridSimTags.END_OF_SIMULATION:
111                                //no action
112                                break;
113                       
114                        case GridSimTags.INFOPKT_SUBMIT:
115                                processPingRequest(ev);
116                                break;
117                               
118                        case GridSimTags.GRIDLET_RETURN:
119                                JobInterface<?> returnedJob = (JobInterface<?>) ev.get_data();
120                               
121                                String jobId = returnedJob.getId();
122
123                               
124                                if (returnedJobs.contains(returnedJob)) {
125                                        if(log.isErrorEnabled())
126                                                log.error("Received the same job twice (job ID " + jobId + ")");
127                                        error = true;
128                                        break;
129                                }
130                               
131                                returnedJobs.add(returnedJob);
132                                returnedJobsIds.add(jobId);
133                               
134                                if(returnedJob.getStatus() == BrokerConstants.JOB_STATUS_FINISHED) {
135                                        if(log.isDebugEnabled())
136                                                log.debug("Received finished job " + jobId);
137                                       
138                                } else {
139                                        if(returnedJob.getStatus() == BrokerConstants.JOB_STATUS_CANCELED) {
140                                                if(log.isWarnEnabled()){
141                                                        String str = "Warning! An uncomplished job (Job ID: "+jobId+") has returned to users. Job was canceled.";
142                                                        log.warn(str);
143                                                }
144                                        }
145                                       
146                                        allTasksAreFinished = false;
147                                }
148                               
149                                counter += returnedJob.getTaskCount();
150                                int remainder = (counter / denominator);
151                                if (remainder != oldRemeinder) {
152                                        int gauge = ((counter * 100) / (workloadLoader.getTaskCount()));
153                                        if(log.isInfoEnabled())
154                                                log.info(gauge + "% ");
155                                       
156                                        oldRemeinder = remainder;
157                                        if (gauge == 100)
158                                                hundredPercent = true;
159                                }
160                       
161                                break;
162                        }
163                       
164                        //if all the Gridlets have been collected
165                        if (counter == workloadLoader.getTaskCount()) {
166                                break;
167                        }
168                       
169                        sim_get_next(ev);
170                }
171               
172                //if all the Gridlets have been collected
173                if (counter == workloadLoader.getTaskCount()) {
174                        if (! hundredPercent) {
175                                if(log.isInfoEnabled())
176                                        log.info("100%");
177                        }
178                        if(log.isInfoEnabled())
179                                log.info(get_name() + ": Received all "+workloadLoader.getJobCount()+" jobs and " + counter + " tasks");                       
180                } else {
181                        if(log.isErrorEnabled())
182                                log.error(get_name() + ": ERROR DID NOT RECEIVED all tasks - some tasks were not finished! (received "+counter+" of "+workloadLoader.getTaskCount()+")");
183                }
184               
185                Iterator <String> itr = sendJobsIds.iterator();
186                String jobId;
187                if(log.isInfoEnabled()){
188                        log.info("Missing tasks: ");
189                        while(itr.hasNext()){
190                                jobId = itr.next();
191                                if(!returnedJobsIds.contains(jobId)){
192                                        log.info(jobId + ", ");
193                                }
194                        }
195                }
196               
197        }
198
199        /**
200         * Sends jobs to broker entities
201         */
202        protected void sendJobs() {
203               
204                Map<Long, List<Job>> jobTimes = new TreeMap<Long, List<Job>>();
205                int destID = GridSim.getEntityId(destName);
206                //destID=GridSim.getEntityId("BROKER@COMPUTING_GRID_0");
207                List<JobDescription> jobs = workloadLoader.getJobs();
208                //TaskRequirements taskReq = new TaskRequirementsImpl();
209                //double values[] = null;
210
211                for (JobDescription job : jobs) {
212                        long l_submissionTime = Long.MAX_VALUE;
213                        //pick the lowest submission time
214                        for (TaskDescription task : job) {
215                                if (task.getSubmissionTime() < l_submissionTime)
216                                        l_submissionTime = task.getSubmissionTime();
217                        }
218
219                        //store the submission time expressed in seconds after the simulation start time
220                        long submissionTime = l_submissionTime;
221                       
222                        Job newJob = prepareJob(job, submissionTime);
223                       
224                        List<Job> list = jobTimes.get(submissionTime);
225                        if (list == null) {
226                                list = new ArrayList<Job>();
227                                jobTimes.put(submissionTime, list);
228                        }
229                        list.add(newJob);
230                }
231                for (Long submissionTime : jobTimes.keySet()) {
232                       
233                        if(submissionTime < submissionStartTime)
234                                submissionStartTime = submissionTime;
235
236                        List<Job> list = jobTimes.get(submissionTime);
237                        for(int i = 0; i < list.size(); i++){
238                                this.sendJobsIds.add(list.get(i).getId());
239                                send(destID, submissionTime, GridSimTags.GRIDLET_SUBMIT, list.get(i));
240                        }
241                       
242                        //send(output, submissionTime, GridSimTags.GRIDLET_SUBMIT, new IO_data(list, GssConstants.DEFAULT_GRIDLET_SIZE, destID));
243                        //send(destID, submissionTime, GridSimTags.GRIDLET_SUBMIT, list);
244                       
245                }
246        }
247       
248        public List<JobDescription> getAllSentJobs() {
249                if (workloadLoader == null)
250                        return new ArrayList<JobDescription>();
251                return (List<JobDescription>) workloadLoader.getJobs();
252        }
253       
254        public List<TaskDescription> getAllSentTasks() {
255                List<TaskDescription> result = new ArrayList<TaskDescription>();
256                List<JobDescription> sentJobs = getAllSentJobs();
257                for (JobDescription job : sentJobs) {
258                        result.addAll(job);
259                }
260                return result;
261        }
262       
263        public List<JobInterface<?>> getAllReceivedJobs() {
264                return returnedJobs;
265        }
266
267        public int getFinishedTasksCount() {
268                int result = 0;
269                for (JobInterface<?> job : returnedJobs) {
270                        for (TaskInterface<?> task: job.getTask()) {
271                                if(task.getStatus() == DCWormsTags.SUCCESS)
272                                        result++;
273                        }
274                }
275                return result;
276        }
277       
278        public String getUserName() {
279                return get_name();
280        }
281       
282        public boolean isError() {
283                return error;
284        }
285       
286        /**
287         * Performs action concerning a ping request to this entity
288         * @param ev the event object
289         */
290        protected void processPingRequest(Sim_event ev) {
291        InfoPacket pkt = (InfoPacket) ev.get_data();
292        pkt.setTag(GridSimTags.INFOPKT_RETURN);
293        pkt.setDestID(pkt.getSrcID());
294
295                // sends back to the sender
296                send(output, GridSimTags.SCHEDULE_NOW, GridSimTags.INFOPKT_RETURN,
297                                new IO_data(pkt, pkt.getSize(), pkt.getSrcID()));
298    }
299               
300        protected Job prepareJob(JobDescription jobDescription, long submissionTime){
301
302                Job newJob = new Job(jobDescription.getJobId());
303                DateTime submitionTime = new DateTime();
304        submitionTime = submitionTime.plusMillis((int)submissionTime*1000);
305                        try {
306                               
307                                // transform job description to resource requirements
308
309                                newJob.setSenderId(this.get_id());
310                               
311                                for (TaskDescription taskDescription : jobDescription) {
312                                       
313                                        String xmlResReq = this.xsltTransformer.taskToResourceRequirements(
314                                                                                taskDescription.getDocument(),
315                                                                                jobDescription.getJobId(),
316                                                                                taskDescription.getUserDn(),
317                                                                                submitionTime);
318
319                                        Task newTask = new Task(xmlResReq);
320                                        newTask.setSenderId(this.get_id());
321                                        newTask.setStatus((int)BrokerConstants.TASK_STATUS_UNSUBMITTED);
322                                        newTask.setLength(taskDescription.getTaskLength());
323                                        newTask.setWorkloadLogWaitTime(taskDescription.getWorkloadLogWaitTime());
324                        //              newTask.setSubmissionTime(taskDescription.getSubmissionTime());
325                                       
326                                        //ENABLES MERGING PRECEDING CONSTRAINST COMING BOTH FROM SWF AND XML FILES
327                                        /*if(taskDescription.getDescription().getWorkflow() != null){
328                                                String precTaskId = taskDescription.getDescription().getWorkflow().getParent(0).getContent();
329                                                if(     newTask.getDescription().getWorkflow() == null){
330                                                        org.qcg.broker.schemas.resreqs.Workflow workflow = new org.qcg.broker.schemas.resreqs.Workflow();
331                                                        org.qcg.broker.schemas.resreqs.ParentType parent = new org.qcg.broker.schemas.resreqs.ParentType();
332                                                        parent.setTriggerState(org.qcg.broker.schemas.resreqs.types.TaskStatesName.FINISHED);
333                                                        parent.setContent(precTaskId);
334                                                        workflow.addParent(parent);
335                                                        newTask.getDescription().setWorkflow(workflow);
336                                                }
337                                        }*/
338                                        newJob.add(newTask);
339                                }
340                                newJob.setStatus((int)BrokerConstants.JOB_STATUS_UNSUBMITTED);
341                                jobDescription.discardUnused();
342                               
343                        } catch (Exception e){
344                                log.error(e.getMessage());
345                                e.printStackTrace();
346                        }
347               
348                return newJob;
349        }
350
351        public long getSubmissionStartTime() {
352                return submissionStartTime;
353        }
354       
355        public boolean isSimStartTimeDefined(){
356                if(workloadLoader == null){
357                        return false;
358                }
359                return workloadLoader.isSimStartTimeDefined();
360        }
361}
Note: See TracBrowser for help on using the repository browser.