<commit_before>package unit

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strings"
	"syscall"

	systemdDbus "github.com/coreos/go-systemd/dbus"
	log "github.com/golang/glog"

	"github.com/coreos/coreinit/job"
	"github.com/coreos/coreinit/machine"
)

const (
	defaultSystemdRuntimePath = "/run/systemd/system/"
)

type SystemdManager struct {
	Systemd    *systemdDbus.Conn
	Target     *SystemdTarget
	Machine    *machine.Machine
	UnitPrefix string
	unitPath   string
}

func NewSystemdManager(machine *machine.Machine, unitPrefix string) *SystemdManager {
	//TODO(bcwaldon): Handle error in call to New()
	systemd, _ := systemdDbus.New()
	systemd.Subscribe()

	name := "coreinit-" + machine.BootId + ".target"
	target := NewSystemdTarget(name)

	mgr := &SystemdManager{systemd, target, machine, unitPrefix, defaultSystemdRuntimePath}

	mgr.writeUnit(target.Name(), "")

	return mgr
}

func (m *SystemdManager) getUnitByName(name string) (*SystemdUnit, error) {
	var unit SystemdUnit
	if strings.HasSuffix(name, ".service") {
		unit = NewSystemdService(m, name)
	} else if strings.HasSuffix(name, ".socket") {
		unit = NewSystemdSocket(m, name)
	} else {
		panic("WAT")
	}

	return &unit, nil
}

func (m *SystemdManager) getUnitsByTarget(target *SystemdTarget) []SystemdUnit {
	info, err := m.Systemd.GetUnitProperties(target.Name())

	if err != nil {
		panic(err)
	}

	names := info["Wants"].([]string)

	var units []SystemdUnit
	for _, name := range names {
		unit, err := m.getUnitByName(name)
		if err == nil {
			units = append(units, *unit)
		} else {
			log.V(1).Infof("Unit %s seems to exist, yet unable to get corresponding SystemdUnit object", name)
		}
	}

	return units
}

func (m *SystemdManager) GetJobs() map[string]job.Job {
	units := m.getUnitsByTarget(m.Target)
	jobs := make(map[string]job.Job, len(units))
	for _, u := range units {
		state := m.getJobStateFromUnit(&u)
		name := m.stripUnitNamePrefix(u.Name())
		j := job.NewJob(name, state, nil)
		jobs[j.Name] = *j
	}

	return jobs
}

func (m *SystemdManager) getJobStateFromUnit(u *SystemdUnit) *job.JobState {
	loadState, activeState, subState, sockets, err := (*u).State()
	if err != nil {
		log.V(1).Infof("Failed to get state for unit %s", (*u).Name())
		return nil
	} else {
		return job.NewJobState(loadState, activeState, subState, sockets, m.Machine)
	}
}

func (m *SystemdManager) GetJobState(j *job.Job) *job.JobState {
	name := m.addUnitNamePrefix(j.Name)
	unit, err := m.getUnitByName(name)
	if err != nil {
		log.V(1).Infof("No local unit corresponding to job %s", j.Name)
		return nil
	}

	return m.getJobStateFromUnit(unit)
}

func (m *SystemdManager) StartJob(job *job.Job) {
	unitFile := NewSystemdUnitFile(job.Payload.Value)
	unitFile.SetField("Install", "WantedBy", m.Target.Name())

	name := m.addUnitNamePrefix(job.Name)
	m.writeUnit(name, unitFile.String())
	m.startUnit(name)
}

func (m *SystemdManager) StopJob(job *job.Job) {
	name := m.addUnitNamePrefix(job.Name)
	m.stopUnit(name)
	m.removeUnit(name)
}

func (m *SystemdManager) getUnitStates(name string) (string, string, string, error) {
	info, err := m.Systemd.GetUnitProperties(name)

	if err != nil {
		return "", "", "", err
	} else {
		loadState := info["LoadState"].(string)
		activeState := info["ActiveState"].(string)
		subState := info["SubState"].(string)
		return loadState, activeState, subState, nil
	}
}

func (m *SystemdManager) startUnit(name string) {
	log.Infof("Starting systemd unit %s", name)

	files := []string{name}
	m.Systemd.EnableUnitFiles(files, true, false)

	m.Systemd.StartUnit(name, "replace")
}

func (m *SystemdManager) stopUnit(name string) {
	log.Infof("Stopping systemd unit %s", name)

	m.Systemd.StopUnit(name, "replace")<commit_msg>chore(logging): expand logging in SystemdManager start/stopUnit<commit_after>package unit

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strings"
	"syscall"

	systemdDbus "github.com/coreos/go-systemd/dbus"
	log "github.com/golang/glog"

	"github.com/coreos/coreinit/job"
	"github.com/coreos/coreinit/machine"
)

const (
	defaultSystemdRuntimePath = "/run/systemd/system/"
)

type SystemdManager struct {
	Systemd    *systemdDbus.Conn
	Target     *SystemdTarget
	Machine    *machine.Machine
	UnitPrefix string
	unitPath   string
}

func NewSystemdManager(machine *machine.Machine, unitPrefix string) *SystemdManager {
	//TODO(bcwaldon): Handle error in call to New()
	systemd, _ := systemdDbus.New()
	systemd.Subscribe()

	name := "coreinit-" + machine.BootId + ".target"
	target := NewSystemdTarget(name)

	mgr := &SystemdManager{systemd, target, machine, unitPrefix, defaultSystemdRuntimePath}

	mgr.writeUnit(target.Name(), "")

	return mgr
}

func (m *SystemdManager) getUnitByName(name string) (*SystemdUnit, error) {
	var unit SystemdUnit
	if strings.HasSuffix(name, ".service") {
		unit = NewSystemdService(m, name)
	} else if strings.HasSuffix(name, ".socket") {
		unit = NewSystemdSocket(m, name)
	} else {
		panic("WAT")
	}

	return &unit, nil
}

func (m *SystemdManager) getUnitsByTarget(target *SystemdTarget) []SystemdUnit {
	info, err := m.Systemd.GetUnitProperties(target.Name())

	if err != nil {
		panic(err)
	}

	names := info["Wants"].([]string)

	var units []SystemdUnit
	for _, name := range names {
		unit, err := m.getUnitByName(name)
		if err == nil {
			units = append(units, *unit)
		} else {
			log.V(1).Infof("Unit %s seems to exist, yet unable to get corresponding SystemdUnit object", name)
		}
	}

	return units
}

func (m *SystemdManager) GetJobs() map[string]job.Job {
	units := m.getUnitsByTarget(m.Target)
	jobs := make(map[string]job.Job, len(units))
	for _, u := range units {
		state := m.getJobStateFromUnit(&u)
		name := m.stripUnitNamePrefix(u.Name())
		j := job.NewJob(name, state, nil)
		jobs[j.Name] = *j
	}

	return jobs
}

func (m *SystemdManager) getJobStateFromUnit(u *SystemdUnit) *job.JobState {
	loadState, activeState, subState, sockets, err := (*u).State()
	if err != nil {
		log.V(1).Infof("Failed to get state for unit %s", (*u).Name())
		return nil
	} else {
		return job.NewJobState(loadState, activeState, subState, sockets, m.Machine)
	}
}

func (m *SystemdManager) GetJobState(j *job.Job) *job.JobState {
	name := m.addUnitNamePrefix(j.Name)
	unit, err := m.getUnitByName(name)
	if err != nil {
		log.V(1).Infof("No local unit corresponding to job %s", j.Name)
		return nil
	}

	return m.getJobStateFromUnit(unit)
}

func (m *SystemdManager) StartJob(job *job.Job) {
	unitFile := NewSystemdUnitFile(job.Payload.Value)
	unitFile.SetField("Install", "WantedBy", m.Target.Name())

	name := m.addUnitNamePrefix(job.Name)
	m.writeUnit(name, unitFile.String())
	m.startUnit(name)
}

func (m *SystemdManager) StopJob(job *job.Job) {
	name := m.addUnitNamePrefix(job.Name)
	m.stopUnit(name)
	m.removeUnit(name)
}

func (m *SystemdManager) getUnitStates(name string) (string, string, string, error) {
	info, err := m.Systemd.GetUnitProperties(name)

	if err != nil {
		return "", "", "", err
	} else {
		loadState := info["LoadState"].(string)
		activeState := info["ActiveState"].(string)
		subState := info["SubState"].(string)
		return loadState, activeState, subState, nil
	}
}

func (m *SystemdManager) startUnit(name string) {
	log.V(1).Infof("Starting systemd unit %s", name)

	files := []string{name}
	m.Systemd.EnableUnitFiles(files, true, false)
	log.V(1).Infof("Enabled systemd unit %s", name)

	m.Systemd.StartUnit(name, "replace")
	log.Infof("Started systemd unit %s", name)
}

func (m *SystemdManager) stopUnit(name string) {
	log.V(1).Infof("Stopping systemd unit %s", name)

	m.Systemd.StopUnit(name, "replace")
	log.Infof("Stopped systemd unit %s", name)
{'fraction_non_alphanumeric': 0.15212002609262884, 'fraction_numerical': 0.0011741682974559687, 'mean_word_length': 4.649226234340457, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '756402', 'n_tokens_mistral': 2905, 'n_tokens_neox': 2808, 'n_words': 627}